Pandas - 按月份累加?

6

我有一个数据框长这个样子:

Date          n
2014-02-27    4
2014-02-28    5
2014-03-01    1
2014-03-02    6
2014-03-03    7

我正在尝试获取一个看起来像这样的页面。
Date          n    csn
2014-02-27    4    4
2014-02-28    5    9
2014-03-01    1    1
2014-03-02    6    7
2014-03-03    7    14

我希望在每个月内都有一个运行总计的列,并且每个月都要重新开始。我该怎么做?

2个回答

10

使用.groupby()函数,但不要只按月分组,而是按年-月进行分组。否则,2013-02将与2014-02等同分组。

In [96]:

df['Month']=df['Date'].apply(lambda x: x[:7])
In [97]:

df['csn']=df.groupby(['Month'])['n'].cumsum()
In [98]:

print df
         Date  n    Month  csn
0  2014-02-27  4  2014-02    4
1  2014-02-28  5  2014-02    9
2  2014-03-01  1  2014-03    1
3  2014-03-02  6  2014-03    7
4  2014-03-03  7  2014-03   14

[5 rows x 4 columns]

4
如果您的数据集是一个DatetimeIndex(应该是这样),您可以直接使用df.groupby(df.index.month) - Jeff
希望这对OP来说是正确的情况。同意应该这样做。但是如果未指定dtype,它将被读取为“object” dtype - CT Zhu
同意。有时候展示给OP看你也应该这样做会有帮助,因为不清楚是如何读取/构建的。 - Jeff
@Jeff,df.index.month忽略年份,通常你需要使用TimeGrouper。 - Andy Hayden
@AndyHayden 啊...是的,这里会很合适。 - Jeff

4

如果你要进行时间序列方面的工作,我建议使用 DatetimeIndex。在这个例子中,你可以使用 TimeGrouper 按月分组(它会按照年-月进行分组,就像 resample 一样):

In [11]: g = df.groupby(pd.TimeGrouper('M'))

In [12]: g['n'].cumsum()
Out[12]: 
Date
2014-02-27     4
2014-02-28     9
2014-03-01     1
2014-03-02     7
2014-03-03    14
dtype: int64

In [13]: df['csn'] = g['n'].cumsum()

注意:如果您还没有使用DatetimeIndex,请跳过to_datetime函数并设置索引:
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)

4
现在更改为 df.groupby(pd.Grouper(freq = 'M')) - user1703276

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接