Filter dataframe value

Viewed 1153

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

5 Answers

df.loc is your friend:

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

Or use eval of pandas:

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

Or (not really recommended), use where of pandas:

df.where(df['value']>20,df['ID'],axis=1).dropna()['ID']

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.

Many ways to solve here.

You can approach this using a vectorized operation. Right now, your code is only evaluating whether a statement is true or false. By wrapping this statement inside of square brackets, you can filter on your Pandas dataframe where all the statements evaluate to True.

So if your dataset looks like

df = pd.DataFrame({'ID': {0: 'A', 1: 'B', 2: 'C'}, 'value': {0: 10, 1: 21, 2: 22}})

You can filter on it: df[df['value'] > 20] or if you want to just receive the values in the ID column, you add on that column's name df[df['value'] > 20]['ID']

You can filter on value

df[df['value'] > 20]

enter image description here

You can filter the columns needed by adding the columns needed at the end

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

enter image description here

Related