首页 > 解决方案 > 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()

但这并不是我想要做的。

标签: pythonpandaspandas-groupby

解决方案


我将此添加为新答案,因为如果有人想要整个组而不是像您现在想要的组的一部分,则先前的答案很有用。

对于您的最新需求,您可以执行以下操作

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

推荐阅读