Reputation: 1654
I'm trying to find out a way how I can select rows in pandas dataframe based that some values will be in my list. For example
df = pd.DataFrame(np.arange(6).reshape(3,2), columns=['A','B'])
A B
0 0 1
1 2 3
2 4 5
I know that I can select certain row, e.g.
df[df.A==0]
will select me row with A=0. What I want is to select multiple rows whose values will be in my list, e.g. A in [0,2]. I tried
df[df.A in [0,2]]
df[list(df.A)==[0,2]]
but nothing works. In R language I can provide %in% operator. In python syntax we can use A in [0,2], etc. How I can select subset of rows in pandas in this case? Thanks, Valentin.
Upvotes: 11
Views: 35493
Reputation: 550
if you don't like that syntax, you can use also use query (introduced in pandas 0.13 which is from 2014):
>>> df.query('A in [0,2]')
A B
0 0 1
1 2 3
Upvotes: 3
Reputation: 1630
pd.isin() will select multiple values:
>>> df[df.A.isin([0,2])]
A B
0 0 1
1 2 3
Upvotes: 30