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

看起来很丑:

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)
)
]

不起作用:

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

对于上述“问题”是否有一个优雅而有效的解决方案?

178684 次浏览

Use isin

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

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.