python - How do sum a value with the previous row value for a pandas dataframe?
问题描述
I have a dataframe where the first two rows look like this:
GOOG AAPL XOM IBM Cash
2009-01-14 0.0 150.0 0.0 0.0 -12745.5
2009-01-15 0.0 0.0 0.0 0.0 -0.0
I want it to add in the previous rows value for each row. So I would want it to look like this:
GOOG AAPL XOM IBM Cash
2009-01-14 0.0 150.0 0.0 0.0 -12745.5
2009-01-15 0.0 150.0 0.0 0.0 -0.0
I do not want it to affect the cash column.
Is there a way to do this easily in pandas?
解决方案
Use DataFrame.cumsum
only for filtered columns by Index.difference
:
c = df.columns.difference(['Cash'])
df[c] = df[c].cumsum()
print (df)
GOOG AAPL XOM IBM Cash
2009-01-14 0.0 150.0 0.0 0.0 -12745.5
2009-01-15 0.0 150.0 0.0 0.0 -0.0
Or by condition with DataFrame.loc
:
c = df.columns != 'Cash'
df.loc[:, c] = df.loc[:, c].cumsum()
推荐阅读
- python - Pywinauto print_control_identifiers 方法超时
- python - 汽车加油问题出现一些错误。它适用于大多数测试用例,但不适用于所有测试用例。你能告诉我为什么这段代码是错误的
- mysql - 替换元素的 SQL 查询
- ios - UICollectionview.performBatchUpdates 更新块不需要在捕获列表中显式使用 self
- forms - React Native - 嵌套对象状态表单构建
- javascript - BigInt 是否代表 64 位的数字?
- python - 在 K 形聚类之后重塑阵列
- reactjs - 如何在反应中禁用所有子组件?
- performance - Odoo14 - 关于limit_memory soft和hard的问题
- python - 如何为熊猫散布颜色参数使用几个分类列