将pandas DataFrame query()方法与isin()结合使用 [英] Combine pandas DataFrame query() method with isin()

查看:510
本文介绍了将pandas DataFrame query()方法与isin()结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想对df.query()使用isin()方法,以在列表中选择id的行:id_list.之前曾问过类似的问题,但是他们使用了典型的df[df['id'].isin(id_list)]方法.我想知道是否可以使用df.query()代替.

So I want to use isin() method with df.query(), to select rows with id in a list: id_list. Similar question was asked before, but they used typical df[df['id'].isin(id_list)] method. I'm wondering if there is a way to use df.query() instead.

df = pd.DataFrame({'a': list('aabbccddeeff'), 'b': list('aaaabbbbcccc'),
                   'c': np.random.randint(5, size=12),
                   'd': np.random.randint(9, size=12)})

id_list = ["a", "b", "c"]

这会产生错误

df.query('a == id_list')

推荐答案

来自

您可以引用变量 在环境中,通过在它们前面添加一个'@'字符,例如 @a + b.

You can refer to variables in the environment by prefixing them with an '@' character like @a + b.

在您的情况下:

In [38]: df.query('a == @id_list')
Out[38]:
   a  b  c  d
0  a  a  3  4
1  a  a  4  5
2  b  a  2  3
3  b  a  1  5
4  c  b  2  4
5  c  b  1  2

这篇关于将pandas DataFrame query()方法与isin()结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆