select 行具有 pandas 数据框中某列的特定值
select rows with certain values of a column in pandas data frames
如果我有一个数据帧 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)]
我想知道是否有其他方法可以做类似的事情。
尝试:
df[df['food'].isin(['apple', 'pear', 'orange', 'grape'])
现代pandas,可以使用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
其中 @
表示 "the following name refers to a variable in the environment, not a column of the frame"。
如果我有一个数据帧 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)]
我想知道是否有其他方法可以做类似的事情。
尝试:
df[df['food'].isin(['apple', 'pear', 'orange', 'grape'])
现代pandas,可以使用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
其中 @
表示 "the following name refers to a variable in the environment, not a column of the frame"。