Search code examples
pythonpandasseries

How to select rows from a series based on values or condition, dynamically?


I have a series produced dynamically, say - df['col1'].value_counts(). I can save this as a series s and then select rows from the series, for e.g., -

s = df['col1'].value_counts()
s_selected = s[s==20]

However I would like to achieve the same dynamically, something like - df['col1'].value_counts().some_function(filtering_condition)

Dataframe has an API like this - df.query()

How to do the same for Series.


Solution

  • Use Series.where chained with dropna

    s.where(lambda x: x == 20).dropna()