CrashLandon
CrashLandon

Reputation: 161

DataFrame optional "condition" to filter nothing

I have a function that modifies a DataFrame, plots things, then returns the updated DataFrame. I want to optionally pass a condition to the function that will be applied to filter the data before plotting.

For example: df[condition].plot()

This will happily plot the contents of df, filtering based on the criteria I provide in condition. But what if sometimes I don't want to filter anything. Is there something simple I can pass in condidtion, so that it essentially behaves like df[:].plot()?

Here's an executable example:

import pandas as pd

df = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]], columns=['a', 'b', 'c'])
df.plot()

condition = df.b != 5
df[condition]           # works fine, filtering out the second row

condition = None
df[condition]           # would like to filter nothing, but raises KeyError```

Upvotes: 1

Views: 438

Answers (1)

rahlf23
rahlf23

Reputation: 9019

You can create a new dataframe that contains all True values that matches the shape of the original dataframe df you are attempting to filter and pass that as your mask:

condition = pd.DataFrame(True, index=np.arange(df.shape[0]), columns=df.columns)

df[condition]

Upvotes: 2

Related Questions