我有以下玩具数据帧(实际的有50万行):
df = pd.DataFrame({'size': list('SSMMMLS'),
'weight': [8, 10, 11, 1, 20, 14, 12],
'adult' : [False] * 5 + [True] * 2})
adult size weight
0 False S 8
1 False S 10
2 False M 11
3 False M 1
4 False M 20
5 True L 14
6 True S 12
而想要GROUPBY adult
,选择该行的这weight
是一个新的列最大,并指定size2
该size
列值:
adult size size2 weight
0 False S S 8
1 False S S 10
2 False M S 11
3 False M S 1
4 False M S 20
5 True L L 14
6 True S L 12
我找到了,但对我不起作用
到目前为止,我有:
df.loc[:, 'size2'] = (df.groupby('adult',as_index=True)['weight','size']
.transform(lambda x: x.ix[x['weight'].idxmax()]['size']))
您可以使用IIUC merge
。我认为insize2
是第一个值M
,因为maxweight
是20
。
df = pd.DataFrame({'size': list('SSMMMLS'),
'weight': [8, 10, 11, 1, 20, 14, 12],
'adult' : [False] * 5 + [True] * 2})
print(df)
adult size weight
0 False S 8
1 False S 10
2 False M 11
3 False M 1
4 False M 20
5 True L 14
6 True S 12
print(
df.groupby('adult')
.apply(lambda subf: subf['size'][subf['weight'].idxmax()]).reset_index(name='size2')
)
adult size2
0 False M
1 True L
print(
pd.merge(df,
df.groupby('adult')
.apply(lambda subf: subf['size'][subf['weight'].idxmax()]
).reset_index(name='size2'), on=['adult'])
)
adult size weight size2
0 False S 8 M
1 False S 10 M
2 False M 11 M
3 False M 1 M
4 False M 20 M
5 True L 14 L
6 True S 12 L
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句