In pandas, the apply() function is commonly employed to apply a function to each row of a DataFrame. However, challenges arise when the previous row value is also calculated using the same apply() method.
Consider the following DataFrame:
Index_Date | A | B | C | D |
---|---|---|---|---|
2015-01-31 | 10 | 10 | NaN | 10 |
2015-02-01 | 2 | 3 | NaN | 22 |
2015-02-02 | 10 | 60 | NaN | 280 |
2015-02-03 | 10 | 100 | NaN | 250 |
The objective is to derive Column C:
To achieve this, we first set the initial value of C for 2015-01-31:
df.loc[0, 'C'] = df.loc[0, 'D']
Then, we iterate through the remaining rows and update the C values with the desired calculations:
for i in range(1, len(df)):
df.loc[i, 'C'] = df.loc[i-1, 'C'] * df.loc[i, 'A'] df.loc[i, 'B']
The final DataFrame after these operations:
Index_Date | A | B | C | D |
---|---|---|---|---|
2015-01-31 | 10 | 10 | 10 | 10 |
2015-02-01 | 2 | 3 | 23 | 22 |
2015-02-02 | 10 | 60 | 290 | 280 |
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3