如果我有一个数据框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)]


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

最佳答案

在现代的熊猫中,可以使用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


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

10-05 20:52
查看更多