我有以下数据框:
我想添加一个新列
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
如果可能的话,我只是在寻找一个简洁的解决方案。
groupby
,对吗?并且可以使用:np.where(test.label == 'bottom', test.loc[test.label.eq('bottom'), 'y'].max(), test.loc[test.label.ne('bottom'), 'y'].min())
。 - ouroboros1