基于列值不同选择不同聚合函数的 Pandas 聚合操作。

3
我有以下数据框:
import pandas as pd
test = pd.DataFrame({'y':[1,2,3,4,5,6], 'label': ['bottom', 'top','bottom', 'top','bottom', 'top']})

y   label
0   1   bottom
1   2   top
2   3   bottom
3   4   top
4   5   bottom
5   6   top

我想添加一个新列 agg_y,如果 label=="bottom",则该列应为 max(y),如果 label=="top",则该列应为 min(y)。我尝试过以下代码:
test['min_y'] = test.groupby('label').y.transform('min')
test['max_y'] = test.groupby('label').y.transform('max')
test['agg_y'] = np.where(test.label == "bottom", test.max_y, test.min_y)
test.drop(columns=['min_y', 'max_y'], inplace=True)

这将会得到正确的结果。

y   label   agg_y
0   1   bottom  5
1   2   top 2
2   3   bottom  5
3   4   top 2
4   5   bottom  5
5   6   top 2

如果可能的话,我只是在寻找一个简洁的解决方案。

1个回答

4

您的一行解决方案是:

test['agg_y'] = np.where(test.label == "bottom",
                         test.groupby('label').y.transform('max'), 
                         test.groupby('label').y.transform('min'))

没有使用groupby的解决方案,感谢@ouroboros1提供:
test['agg_y'] = np.where(test.label == 'bottom', 
                         test.loc[test.label.eq('bottom'), 'y'].max(), 
                         test.loc[test.label.ne('bottom'), 'y'].min())

另一个想法是映射值,这个想法与ouroboros1的解决方案相似:

d = {'bottom':'max', 'top':'min'}
test['agg_y'] = test['label'].map({val:test.loc[test.label.eq(val),'y'].agg(func) 
                                   for val, func in d.items()})

print (test)
   y   label  agg_y
0  1  bottom      5
1  2     top      2
2  3  bottom      5
3  4     top      2
4  5  bottom      5
5  6     top      2

1
我觉得在这种情况下你可以避免使用groupby,对吗?并且可以使用:np.where(test.label == 'bottom', test.loc[test.label.eq('bottom'), 'y'].max(), test.loc[test.label.ne('bottom'), 'y'].min()) - ouroboros1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接