[英]How to add a column to a grouped by DataFrame from the original DataFrame - Python
我有这个 DataFrame:
Name Year Publisher Global_Sales
0 Wii Sports 2006.0 Nintendo 82.74
1 Super Mario Bros. 1985.0 Nintendo 40.24
2 Mario Kart Wii 2008.0 Nintendo 35.82
3 Wii Sports Resort 2009.0 Nintendo 33.00
4 Pokemon Red/Pokemon Blue 1996.0 Nintendo 31.37
我想按年份对其进行分组并查看每年的最大 Global_Sales:
comp_group=df_comparation.groupby('Year')['Global_Sales'].max()
我得到:
Year
1980.0 4.31
1981.0 4.50
1982.0 7.81
1983.0 3.20
1984.0 28.31
1985.0 40.24
1986.0 6.51
1987.0 4.38
1988.0 17.28
1989.0 30.26
1990.0 20.61
现在我想知道 Publisher 制作了最大 Global_Sales 并将其添加为列:
Year Global_Sales Publisher
1980.0 4.31 Nintendo
1981.0 4.50 EA Sports
1982.0 7.81 ...
1983.0 3.20 ...
1984.0 28.31 ...
1985.0 40.24 ...
1986.0 6.51 ...
1987.0 4.38 ...
1988.0 17.28 ...
1989.0 30.26 ...
1990.0 20.61 ...
谢谢!
您可以使用.idxmax()
进行聚合以获取每年最大销售额的索引,然后对其进行索引以获得结果:
indexes = df.groupby("Year")["Global_Sales"].idxmax()
result = df.loc[indexes, ["Year", "Global_Sales", "Publisher"]]
按Year
对 dataframe 进行分组,然后应用 function 以获得 Global_Sales 和 Publisher 以获得最大 Global_Sales:
(df
.groupby('Year')
.apply(lambda x: x.loc[x['Global_Sales'].idxmax(), ['Global_Sales', 'Publisher']])
)
Global_Sales Publisher
Year
1985.0 40.24 Nintendo
1996.0 31.37 Nintendo
2006.0 82.74 Nintendo
2008.0 35.82 Nintendo
2009.0 33.00 Nintendo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.