【问题标题】:How to do accumulative calculation in data frame in Python?如何在 Python 中的数据框中进行累积计算?
【发布时间】:2018-02-13 03:16:18
【问题描述】:

我有一个这样的数据框,

import pandas as pd
d = {'col1': ["2004-02-26", "2004-02-27", "2004-03-01",
              "2004-03-02", "2004-03-03", "2004-03-04",
              "2004-03-05", "2004-03-08", "2004-03-09",
              "2004-03-10", "2004-03-11", "2004-03-12"],
     'col2': [3, 4, 5, 3, 1, 11, 123, 43, 5, 3, 4, 7],
     'col3': [-1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1]}
df = pd.DataFrame(data=d)

        col1  col2  col3
0   2004-02-26     3    -1
1   2004-02-27     4     1
2   2004-03-01     5    -1
3   2004-03-02     3    -1
4   2004-03-03     1     1
5   2004-03-04    11     1
6   2004-03-05   123     1
7   2004-03-08    43     1
8   2004-03-09     5    -1
9   2004-03-10     3     1
10  2004-03-11     4     1
11  2004-03-12     7    -1

假设现在我从一开始就有 1000 现金。当col3 为负时,我持有我的钱。当它变为正数时,我把钱投入并乘以 col2 的值,直到它遇到下一个 -1 我再次收回所有的钱。

所有计算值都存储在新列“col4”中。最后数据框看起来像,

       col1      col2  col3   col4
0   2004-02-26     3    -1    1000
1   2004-02-27     4     1    4000
2   2004-03-01     5    -1    4000
3   2004-03-02     3    -1    4000
4   2004-03-03     1     1    4000
5   2004-03-04    11     1    44000
6   2004-03-05   123     1    492000
7   2004-03-08    43     1    172000
8   2004-03-09     5    -1    172000
9   2004-03-10     3     1    516000
10  2004-03-11     4     1    688000
11  2004-03-12     7    -1    688000

【问题讨论】:

  • 你试过cumulative sum吗?
  • 嗨@akrun 这是系统建议的标签..
  • 输出对吗? 17200 应该是 172000
  • @Wen Ahhh...我应该在发布之前检查它...
  • 嗨,@excaza 我试过这个,但看起来有点不同。

标签: python pandas numpy dataframe


【解决方案1】:

cumprodwherefillna 一起使用:

df['col4'] = (((df.col3.where(df.col3.gt(0))*df.col2)
               .fillna(1)
               .cumprod())
               .astype(int).mul(1000))

输出:

          col1  col2  col3        col4
0   2004-02-26     3    -1        1000
1   2004-02-27     4     1        4000
2   2004-03-01     5    -1        4000
3   2004-03-02     3    -1        4000
4   2004-03-03     1     1        4000
5   2004-03-04    11     1       44000
6   2004-03-05   123     1     5412000
7   2004-03-08    43     1   232716000
8   2004-03-09     5    -1   232716000
9   2004-03-10     3     1   698148000
10  2004-03-11     4     1  2792592000
11  2004-03-12     7    -1  2792592000

【讨论】:

  • 是的,我认为这符合 OP 使用的措辞,而不是我不确定其中一些数字来自哪里的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 2015-06-29
  • 2020-03-19
相关资源
最近更新 更多