简体   繁体   中英

How can i create a new dataframe with cell values based on the previous row for each column?

I´m very new in python, so i need to ask this question:

I have this dataframe:

数据框

I need to know how I can obtain a new dataframe with this result:

新数据框

Starting in the second row (index 1), the formula to be applied is: previous row cell value *(1+actual cell value) .

You can calculate the cumulative product of the rows after the first using .cumprod() . Here I take the second row onwards, add 1 to these and calculate the cumulative product. I then multiply this by the first row.

(df.iloc[1:]+1).cumprod() * df.iloc[0]

And then concatenate the first row of your dataframe df.head(1) with the calculated dataframe using pd.concat() :

pd.concat([df.head(1), ((df.iloc[1:]+1).cumprod() * df.iloc[0])], ignore_index=True)

This can be split in to parts:

# calculation
df2 = (df.iloc[1:]+1).cumprod() * df.iloc[0]
# concatenate the first row of df with the calculation
pd.concat([df.head(1), df2], ignore_index=True)

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