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

Linda Hamilton
Release: 2024-11-03 19:26:02
Original
407 people have browsed it

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_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:

  • 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:

<code class="python">df.loc[0, 'C'] = df.loc[0, 'D']</code>
Copy after login

Then, we iterate through the remaining rows and update the C values with the desired calculations:

<code class="python">for i in range(1, len(df)):
    df.loc[i, 'C'] = df.loc[i-1, 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']</code>
Copy after login

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

The above is the detailed content of How to Calculate a Column in a DataFrame Using Previous Row Values with `apply()`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!