1

Given a dataframe df, I'd apply some condition df[condition] and retrieve a subset. I just want to check if there are any rows in the subset - this would tell me the condition is a valid one.

In [551]: df
Out[551]: 
   Col1
0     1
1     2
2     3
3     4
4     5
5     3
6     1
7     2
8     3

What I want to check is something like this:

if df[condition] has rows:
    do something

What is the best way to check whether a filtered dataframe has rows? Here's some methods that don't work:

  1. if df[df.Col1 == 1]: Gives ValueError: The truth value of a DataFrame is ambiguous.

  2. if df[df.Col1 == 1].any(): Also gives ValueError

I suppose I can test the len. Are there other ways?

cs95
  • 379,657
  • 97
  • 704
  • 746

1 Answers1

8

You could use df.empty:

df_conditional = df.loc[df['column_name'] == some_value]
if not df_conditional.empty:
    ... # process dataframe results
cs95
  • 379,657
  • 97
  • 704
  • 746
RHSmith159
  • 1,823
  • 9
  • 16
  • 2
    https://stackoverflow.com/questions/19828822/how-to-check-whether-a-pandas-dataframe-is-empty suggests that using `len` is faster .Worth to check out – Jean-François Fabre Aug 20 '17 at 08:56