Filter dataframe value

1507 views python
5

I have a dataframe that I want to filter by value more than 20

ID   value
A    10
B    21
C    22

I used df['ID'] > 20 and received result

False
True
True

However, I want it to return B, C, not boolean value

answered question

3 Answers

12

Select only rows where value > 20, then return the values of ID

import pandas as pd
df = {"ID": ["A", "B", "C"], "val":[10, 21, 22]}
df = pd.DataFrame(df)

df = df[df["val"] > 20]
df["ID"].values

Returns:

array(['B', 'C'], dtype=object)

Edit: the answers here using df.loc do the same steps as above, only better and in a more concise way. I'll leave this up in case it's explanatory for anyone.

posted this
2

df.loc is your friend:

df.loc[df['value'] > 20, 'ID']

posted this
7

Or use eval of pandas:

df.loc[df.eval('value > 20'),'ID']

posted this

Have an answer?

JD

Please login first before posting an answer.