【问题标题】:Dynamic cumulative summations in PandasPandas 中的动态累积求和
【发布时间】:2017-05-16 15:00:56
【问题描述】:

在以下 DataFrame 中,列 B 计算列 A 从索引 0 到 n 的总和。

ix    A      B
---------------
 0     1     1
 1     1     2
 2     1     3
 3     1     4
 4     2     6
 5    -1     5
 6    -3     2

或者,B 列对每个 type == 'I' 和 -1 求和 1 对于每个 type == 'O'。

ix   type     B
----------------
 0      I     1
 1      I     2
 2      O     1
 3      I     2
 4      O     1
 5      O     0
 6      I     1

如何执行这种类型的计算,其中一列的n-th结果取决于另一列的聚合结果,最多n?

【问题讨论】:

  • 看看cumsum和expanding。
  • @IanS 应该可以解决问题!谢谢

标签: python pandas dictionary replace cumsum


【解决方案1】:

你可以使用cumsum:

df['C'] = df.A.cumsum()
print (df)
   ix  A  B  C
0   0  1  1  1
1   1  1  2  2
2   2  1  3  3
3   3  1  4  4
4   4  2  6  6
5   5 -1  5  5
6   6 -3  2  2

第二个df 添加map dict:

df['C'] = df.type.map({'I':1, 'O':-1}).cumsum()
print (df)
   ix type  B  C
0   0    I  1  1
1   1    I  2  2
2   2    O  1  1
3   3    I  2  2
4   4    O  1  1
5   5    O  0  0
6   6    I  1  1

或者:

df['C'] = df.type.replace({'I':1, 'O':-1}).cumsum()
print (df)
   ix type  B  C
0   0    I  1  1
1   1    I  2  2
2   2    O  1  1
3   3    I  2  2
4   4    O  1  1
5   5    O  0  0
6   6    I  1  1

【讨论】:

    猜你喜欢
    • 2019-02-15
    • 2019-10-29
    • 2017-01-30
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2019-10-05
    相关资源
    最近更新 更多