Issue
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)
.
Solution
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)
Answered By - Rawson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.