在pandas数据框中选择具有某列值的行

时间:2015-01-30 03:56:55

标签: python performance numpy pandas dataframe

如果我有一个数据帧df如下:

   food      price   amount
0  apple      2.0     3
1  grape      3.0     20
2  orange     1.9     3.0
3  pork       3.0     0.5
4  lattice    1.0     1.0
5  pear       3.0     2
6  zucchini   2.5     1
7  pumpkin    2.0     0.5
8  grape      3.0     30

我有以下np.array:

fruit = np.array([apple, pear, orange, grape])

我想仅在食物名称在水果数组中时才提取数据框中的行。到目前为止,我有以下代码,它给出了我想要的东西:

df[df['food'].apply(lambda x: x in fruit)]

我想知道是否有其他方法可以做类似的事情。

2 个答案:

答案 0 :(得分:2)

尝试:

df[df['food'].isin(['apple', 'pear', 'orange', 'grape'])

答案 1 :(得分:2)

在现代熊猫中,您可以使用DataFrames的query方法:

>>> fruit = np.array(["apple", "pear", "orange", "grape"])
>>> df.query("food in @fruit")
     food  price  amount
0   apple    2.0       3
1   grape    3.0      20
2  orange    1.9       3
5    pear    3.0       2
8   grape    3.0      30

其中@表示“以下名称是指环境中的变量,而不是框架的列”。