python - Pandas - 在一列中返回具有相同值的所有行,在另一列中返回小的差异
问题描述
我有一些数据框:
df = pd.DataFrame({'fruit':['apple', 'apple', 'apple', 'pear', 'pear', 'pear', 'mango', 'mango', 'mango', 'peach', 'peach', 'peach', 'plum', 'plum', 'plum'],
'region':[5,5,5,7,7,7,2,2,2,2,2,2,2,2,2],
'location':[75000,75000,75000,250,250,250,48897467,48897467,48897467,48897629,48897629,48897629,500000000,500000000,500000000],
'unique':np.random.randint(100, size=15)})
fruit region location unique
0 apple 5 75000 51
1 apple 5 75000 1
2 apple 5 75000 44
3 pear 7 250 36
4 pear 7 250 86
5 pear 7 250 99
6 mango 2 48897467 40
7 mango 2 48897467 12
8 mango 2 48897467 33
9 peach 2 48897629 23
10 peach 2 48897629 85
11 peach 2 48897629 65
12 plum 2 500000000 46
13 plum 2 500000000 87
14 plum 2 500000000 42
我想选择列中'fruit'
具有相同值且'region'
列中差异小于 1000 的所有不同行'location'
。
所以,在这个例子中,我想返回:
fruit region location unique
6 mango 2 48897467 40
7 mango 2 48897467 12
8 mango 2 48897467 33
9 peach 2 48897629 23
10 peach 2 48897629 85
11 peach 2 48897629 65
我试过类似的东西:
df.groupby('region')['location'].diff()
但这并不是我想要做的。
解决方案
我将此添加为新答案,因为如果有人想要整个组而不是像您现在想要的组的一部分,则先前的答案很有用。
对于您的最新需求,您可以执行以下操作
def func(x):
return (x - x.iloc[0])
a = df.groupby('region')['location'].apply(func)
b = df.groupby('region')['fruit'].transform('nunique')
df.loc[(a<=1000) & (b>1)]
这仅适用于location
按升序排序的列(请确保在开始之前按区域和位置对 df 进行排序)。
输出
fruit region location unique
6 mango 2 48897467 79
7 mango 2 48897467 62
8 mango 2 48897467 68
9 peach 2 48897629 71
10 peach 2 48897629 64
11 peach 2 48897629 69
推荐阅读
- android - react-native-navigation 如何关闭应用通知
- android - Retrofit&Gson从标题和cookie分配字段?
- onclick - Vue.js - 无法添加点击事件
- javascript - JSX 是什么以及它在 React 中的真正作用是什么?
- android - 我如何将数据解析到列表视图中?
- c++ - Is there any difference in equality checks on right or left changing value in if condition
- selenium - 如何同时在多台服务器上运行我的 selenium 脚本,以便我可以一一节省执行时间?
- node.js - 尝试验证附加到用户基础模型的模型时,Loopback 3 崩溃
- docker - 如何使用 docker exec 安装 Composer
- python - Pandas convert datatime format