熊猫如何使用一年以上的数据每月重新抽样



我有一个数据框架,它是7年数据的时间序列。我有一个索引是timestamp和一列(我们叫它sales)对于每个store。每个商店都有自己的sales时间序列。

我正试图重新采样并将所有数据汇总为月度可视化,如下所示:

df = df.groupby('store').resample('M').sum()

这确实是按月分组数据,但它考虑了年。也就是说,它将"2010年12月"与"2011年12月"视为不同的月份。我最终有7 * 12行,而不是只有12行。

我想把这7年中所有月份的销售额加起来,并把它们按12个月的销售额分组。

最小可复制示例

index = pd.date_range('1/1/2000', periods=730, freq='D') #2 years of daily data
series = pd.Series(range(730), index=index) #just dummy data
series # would return a index with 730 values (2 years)
series.resample('M').sum() #this returns 24 values, representing each month, which doesn't work for me.

感谢

您可能希望使用df并通过对日期应用函数来添加一列,以获得月份。你也可以通过groupby中的应用功能,但我不确定这将如何工作,这种方法会给你你想要的结果

import pandas as pd
dates = pd.date_range('1/1/2000', periods=730, freq='D') #2 years of daily data
series = pd.Series(range(730)) #just dummy data
# make temp df
d = {'date': dates, 'temp': series}
df = pd.DataFrame(d)
# add col just for month
df['month_num'] = df.apply(lambda row: str(row['date']).split('-')[1], axis=1)
print(df)
# get sum for each month
print(df.groupby('month_num')['temp'].sum())

df生成:

date  temp month_num
0   2000-01-01     0        01
1   2000-01-02     1        01
2   2000-01-03     2        01
3   2000-01-04     3        01
4   2000-01-05     4        01
..         ...   ...       ...
725 2001-12-26   725        12
726 2001-12-27   726        12
727 2001-12-28   727        12
728 2001-12-29   728        12
729 2001-12-30   729        12
[730 rows x 3 columns]
groupby month_num sum():

month_num
01    12276
02    12799
03    15965
04    17280
05    19747
06    20940
07    23529
08    25451
09    26460
10    29233
11    30120
12    32285
Name: temp, dtype: int64

试试这个,使用pd.DatetimeIndexmonth属性:

series.groupby(series.index.month).sum()

输出:

1     12276
2     12799
3     15965
4     17280
5     19747
6     20940
7     23529
8     25451
9     26460
10    29233
11    30120
12    32285
dtype: int64

最新更新