[英]Find max by year and return date on which max occurred in Pandas with dates as index
[英]Find max by year and return date on which max occurred in Pandas DataFrame
假设我有一个自 2010 年以来每天卖出的糖果数量。对于每一年(2010、2011、2012...2019),我如何找到我使用 Pandas 卖出最多糖果的日期?
date Count
01/01/2010 525
01/02/2010 136
01/03/2010 125
01/04/2010 84
01/05/2010 446
...
01/01/2011 301
01/02/2011 700
...
11/16/2019 807
我试过这个,它给了我每年的最大值,但我想要每年的日期和计数。
df.groupby(lambda x: df['date'][x].year)["Count"].max()
date Count
2010 825
2011 973
2012 900
2013 830
2014 879
2015 690
2016 827
2017 954
2018 1032
2019 968
谢谢您的帮助!
将您的代码更改修复为idxmax
idx = df.groupby(lambda x: df['date'][x].year)["Count"].idxmax()
out = df.loc[idx]
假设您的date
列由熊猫时间戳组成,您可以使用dt
日期访问器方法来访问对年度总和进行分组的year
属性:
gb = df.groupby(df['date'].dt.year)['Count'].sum()
max_year = gb.idxmax()
max_annual_sales = gb.loc[max_year]
如果没有,首先通过df['date'] = pd.to_datetime(df['date'])
转换它们。
然后使用idxmax
方法获取包含最大年度计数的年份索引。 最后,使用今年通过gb.loc[max_year]
找到最大值(或仅使用gb.max()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.