Python 如何检查值是否在从熊猫数据框中选择的列表中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18250298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:18:12  来源:igfitidea点击:

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

pythonselectnumpypandasdataframe

提问by Roman

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"?

上述“问题”是否有优雅且有效的解决方案?

采纳答案by waitingkuo

Use isin

使用isin

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

回答by jpp

You can use pd.DataFrame.query:

您可以使用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.evalfunction.

在后台,这使用顶级pd.eval函数。