本文介绍了 pandas 数据框集团年指数(按十年)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个索引为每月时间步长的数据框,我知道我可以使用dataframe.groupby(lambda x:x.year)将每月数据分组为每年并应用其他操作.我有什么办法可以快速地将它们分组,比如说十年?

suppose I have a dataframe with index as monthy timestep, I know I can use dataframe.groupby(lambda x:x.year) to group monthly data into yearly and apply other operations. Is there some way I could quick group them, let's say by decade?

感谢任何提示.

推荐答案

要获得十年,您可以将年份整数除以10,然后乘以10.例如,如果您从

To get the decade, you can integer-divide the year by 10 and then multiply by 10. For example, if you're starting from

>>> dates = pd.date_range('1/1/2001', periods=500, freq="M")
>>> df = pd.DataFrame({"A": 5*np.arange(len(dates))+2}, index=dates)
>>> df.head()
             A
2001-01-31   2
2001-02-28   7
2001-03-31  12
2001-04-30  17
2001-05-31  22

您可以像往常一样按年份分组(这里有一个DatetimeIndex,这很简单):

You can group by year, as usual (here we have a DatetimeIndex so it's really easy):

>>> df.groupby(df.index.year).sum().head()
         A
2001   354
2002  1074
2003  1794
2004  2514
2005  3234

或者您可以执行(x//10)*10技巧:

>>> df.groupby((df.index.year//10)*10).sum()
           A
2000   29106
2010  100740
2020  172740
2030  244740
2040   77424

如果没有可以使用.year的东西,您仍然可以使用lambda x: (x.year//10)*10).

If you don't have something on which you can use .year, you could still do lambda x: (x.year//10)*10).

这篇关于 pandas 数据框集团年指数(按十年)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 04:43