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.
To select the rows from a Pandas DataFrame based on input values, we can use the isin() method.
You can select the Rows from Pandas DataFrame based on column values or based on multiple conditions either using DataFrame. loc[] attribute, DataFrame. query() or DataFrame. apply() method to use lambda function.
pd.isin() will select multiple values:
>>> df[df.A.isin([0,2])]
A B
0 0 1
1 2 3
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With