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

Time:05-12

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

I have this dataframe:

data frame

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

new data frame

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

CodePudding user response:

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)
  • Related