Pandas:比较组内的行

Mar*_*bak 5 python pandas pandas-groupby

我有一个按“键”分组的数据框。我需要比较每个组中的行,以确定是要保留组中的每一行还是只需要一组中的一行。

在保留一组所有行的条件下:如果有一行颜色为“红色”,面积为“12”,形状为“圆形”,另一行(同一组内)的颜色为“绿色”和“13”的区域和“正方形”的形状,然后我想保留该组中的所有行。否则,如果这种情况不存在,我想保留该组中具有最大 'num' 值的行。

df = pd.DataFrame({'KEY': ['100000009', '100000009', '100000009', '100000009', '100000009','100000034','100000034', '100000034'], 
              'Date1': [20120506, 20120506, 20120507,20120608,20120620,20120206,20120306,20120405],
              'shape': ['circle', 'square', 'circle','circle','circle','circle','circle','circle'],
              'num': [3,4,5,6,7,8,9,10],
              'area': [12, 13, 12,12,12,12,12,12],
              'color': ['red', 'green', 'red','red','red','red','red','red']})


    Date1       KEY        area color   num shape
0   2012-05-06  100000009   12  red     3   circle
1   2012-05-06  100000009   13  green   4   square
2   2012-05-07  100000009   12  red     5   circle
3   2012-06-08  100000009   12  red     6   circle
4   2012-06-20  100000009   12  red     7   circle
5   2012-02-06  100000034   12  red     8   circle
6   2012-03-06  100000034   12  red     9   circle
7   2012-04-05  100000034   12  red     10  circle
Run Code Online (Sandbox Code Playgroud)

预期结果:

    Date1       KEY        area color   num shape
0   2012-05-06  100000009   12  red     3   circle
1   2012-05-06  100000009   13  green   4   square
2   2012-05-07  100000009   12  red     5   circle
3   2012-06-08  100000009   12  red     6   circle
4   2012-06-20  100000009   12  red     7   circle
7   2012-04-05  100000034   12  red     10  circle
Run Code Online (Sandbox Code Playgroud)

我是 python 新手,groupby 给我扔了一个曲线球。

maxnum = df.groupby('KEY')['num'].transform(max)
df = df.loc[df.num == maxnum]

cond1 = (df[df['area'] == 12]) & (df[df['color'] == 'red']) & (df[df['shape'] == 'circle'])
cond2 = (df[df['area'] == 13]) & (df[df['color'] == 'green']) & (df[df['shape'] == 'square'])
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 3

定义一个名为的自定义函数function

def function(x):
    i = x.query(
        'area == 12 and color == "red" and shape == "circle"'
    )
    j = x.query(
        'area == 13 and color == "green" and shape == "square"'
    )
    return x if not (i.empty or j.empty) else x[x.num == x.num.max()].head(1)
Run Code Online (Sandbox Code Playgroud)

此函数在指定条件下测试每个组并根据需要返回行。特别是,它使用 查询条件并测试是否为空df.empty

将其传递给groupby+ apply

df.groupby('KEY', group_keys=False).apply(function)


      Date1        KEY  area  color  num   shape
0  20120506  100000009    12    red    3  circle
1  20120506  100000009    13  green    4  square
2  20120507  100000009    12    red    5  circle
3  20120608  100000009    12    red    6  circle
4  20120620  100000009    12    red    7  circle
7  20120405  100000034    12    red   10  circle
Run Code Online (Sandbox Code Playgroud)