微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – Pandas:每n行累计和

我有一个数据框,其列“日期”类型为dtype M8 [ns],另一个是“expected_response”.然后,有一列“cumulative_expected”,它使具有相同日期的行之间的expected_response的累积和.数据框在每个月的每一秒都有一行.如下所示:

               date Expected_response cumulative_expected
       0    2018-03-01  0.270   0.270
       1    2018-03-01  0.260   0.530
       2    2018-03-01  0.240   0.770
       3    2018-03-01  0.224   0.994
       4    2018-03-01  0.204   1.198
       5    2018-03-01  0.194   1.392
       6    2018-03-01  0.190   1.582
       ...  ...     ...     ...
2678395     2018-03-31  0.164   -7533.464
2678396     2018-03-31  0.164   -7533.300
2678397     2018-03-31  0.160   -7533.140
2678398     2018-03-31  0.154   -7532.986
2678399     2018-03-31  0.150   -7532.836

如您所见,存在错误:累计金额无法识别日期的更改,并且每次日期更改时累计金额不会重新开始.

代码是:

DF [ ‘cumulative_expected’] = df.groupby(DF [ ‘日期’]!= DF [ ‘日期’])[ ‘Expected_response’].cumsum()

也许一个选项可能是创建一个计数器,每86400行(一天中的几秒)增加1,然后由计数器组合.但我不知道该怎么做.

还有其他解决方案吗?
先感谢您

解决方法:

认索引,所以你可以使用楼层划分:

df['cumulative_expected'] = df['Expected_response'].groupby(df.index // 86400).cumsum()

通常解决方案是使用楼层划分创建np.arange:

arr = np.arange(len(df)) // 86400
df['cumulative_expected'] = df['Expected_response'].groupby(arr).cumsum()

应该通过将shifted值与cumsum进行比较来更改您的解决方案:

s = (df['date']!=df['date'].shift()).cumsum()
df['cumulative_expected'] = df['Expected_response'].groupby(s).cumsum()

测试更改的样本数据:

print (df)

         date  Expected_response
0  2018-03-01              0.270
1  2018-03-01              0.260
2  2018-03-02              0.240
3  2018-03-02              0.224
4  2018-03-02              0.204
5  2018-03-01              0.194
6  2018-03-01              0.190

s = (df['date']!=df['date'].shift()).cumsum()
print (s)
0    1
1    1
2    2
3    2
4    2
5    3
6    3
Name: date, dtype: int32

df['cumulative_expected'] = df['Expected_response'].groupby(s).cumsum()
print (df)
        date  Expected_response  cumulative_expected
0 2018-03-01              0.270                0.270
1 2018-03-01              0.260                0.530
2 2018-03-02              0.240                0.240
3 2018-03-02              0.224                0.464
4 2018-03-02              0.204                0.668
5 2018-03-01              0.194                0.194
6 2018-03-01              0.190                0.384

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐