首页 > 解决方案 > 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?

标签: pythonpandas

解决方案


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()

推荐阅读