简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM