[英]Find max of group return entire row pandas
Forgive if this is a duplicate. 如果这是重复的,请原谅。 It seems like it should be, but I've searched all the suggested and more. 看起来应该如此,但我已经搜索了所有建议的内容和更多内容。
I have this table 我有这张桌子
Look_Back_Months Total Spread Return sector
10 11 0.038961 Apartment
20 21 0.078029 Apartment
30 31 0.079272 Apartment
40 5 0.013499 Office
50 15 0.018679 Office
60 25 -0.003378 Office
I'd like to return 我想回来
Look_Back_Months Total Spread Return sector
30 31 0.079272 Apartment
50 15 0.018679 Office
Have tried groupby
, agg
and I keep returning either the max Look_Back_Months and the Total Spread Return. 尝试过groupby
, agg
,我一直返回最大Look_Back_Months 和总价差回报。 Or just one or the other. 或者只是一个或另一个。
Thanks 谢谢
By using 通过使用
df.sort_values('TotalSpreadReturn').drop_duplicates('sector',keep='last')
Out[270]:
Look_Back_Months TotalSpreadReturn sector
50 15 0.018679 Office
30 31 0.079272 Apartment
You can use groupby.max
with transform
. 您可以将groupby.max
与transform
groupby.max
使用。
g = df.groupby('sector')['TotalSpreadReturn'].transform('max')
res = df[df['TotalSpreadReturn'] == g]
print(res)
Look_Back_Months TotalSpreadReturn sector
30 31 0.079272 Apartment
50 15 0.018679 Office
If it matters, this includes duplicate maximums and maintains index order. 如果重要的话,这包括重复的最大值并保持索引顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.