gpt4 book ai didi

python - 在 pandas 数据框中选择具有特定列值的行

转载 作者:太空宇宙 更新时间:2023-11-04 10:28:40 25 4
gpt4 key购买 nike

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

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

最佳答案

在现代 Pandas 中,您可以使用 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

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

关于python - 在 pandas 数据框中选择具有特定列值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28229002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com