RDJ RDJ - 1 month ago 13
Python Question

Pandas: return dataframe where one column's values are greater than another

Apologies if this is a duplicate but I can't seem to find a working example in the pandas docs, SO or google.

How do you return a dataframe where the values of one column are greater than the values of another?

Should be something like this:

df['A'].where(df['A']>df['B'])


But this returns only a vector. I need the full filtered dataframe.

Answer

Try using query

df.query('A > B')

consider df

np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(10, 2), columns=list('AB'))
df

enter image description here

option 1

df.query('A > B')

option 2

df[df.A.gt(df.B)]

enter image description here

Comments