"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Calculate a Column in a DataFrame Using Previous Row Values with `apply()`?

How to Calculate a Column in a DataFrame Using Previous Row Values with `apply()`?

Published on 2024-11-13
Browse:764

How to Calculate a Column in a DataFrame Using Previous Row Values with `apply()`?

Iterating Through DataFrames with Previous Value Considerations Using apply()

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_DateABCD
2015-01-311010NaN10
2015-02-0123NaN22
2015-02-021060NaN280
2015-02-0310100NaN250

The objective is to derive Column C:

  • For 2015-01-31, set it to the value of D.
  • For subsequent rows, multiply the previous row value of C by the current row value of A and add it to the current row value of B.

Solution:

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_DateABCD
2015-01-3110101010
2015-02-01232322
2015-02-021060290280
Latest tutorial More>

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