How to check if a value is in the list in selection from pandas data frame?

PythonSelectNumpyPandasDataframe

Python Problem Overview


Looks ugly:

df_cut = df_new[             (             (df_new['l_ext']==31) |
             (df_new['l_ext']==22) |
             (df_new['l_ext']==30) |
             (df_new['l_ext']==25) |
             (df_new['l_ext']==64)
             )
            ]

Does not work:

df_cut = df_new[(df_new['l_ext'] in [31, 22, 30, 25, 64])]

Is there an elegant and working solution of the above "problem"?

Python Solutions


Solution 1 - Python

Use isin

df_new[df_new['l_ext'].isin([31, 22, 30, 25, 64])]

Solution 2 - Python

You can use pd.DataFrame.query:

select_values = [31, 22, 30, 25, 64]
df_cut = df_new.query('l_ext in @select_values')

In the background, this uses the top-level pd.eval function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRomanView Question on Stackoverflow
Solution 1 - PythonwaitingkuoView Answer on Stackoverflow
Solution 2 - PythonjppView Answer on Stackoverflow