Home > Backend Development > Python Tutorial > How to Calculate a Column Based on Previous Row Values in Pandas Using the `apply()` Function?

How to Calculate a Column Based on Previous Row Values in Pandas Using the `apply()` Function?

Mary-Kate Olsen
Release: 2024-10-29 20:58:29
Original
742 people have browsed it

How to Calculate a Column Based on Previous Row Values in Pandas Using the `apply()` Function?

Applying Calculations with Previous Row Values in Pandas

In Pandas, encountering the challenge of incorporating previous row values into calculations during data manipulation is not uncommon. One such scenario involves the need to use the previous row value when calculating a new column using the apply() function.

Consider a scenario where we have a DataFrame with the following structure:

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
Copy after login

Our goal is to populate the 'C' column with calculated values. For the first row, 'C' is derived from 'D'. For subsequent rows, 'C' is calculated by multiplying the previous row's 'C' value by the 'A' value for the current row and adding the 'B' value.

Approach

To achieve this, we employ a combination of initialization and iteration within the apply() function.

  1. Initialize the 'C' value for the first row using the value from 'D'.
<code class="python">df.loc[0, 'C'] = df.loc[0, 'D']</code>
Copy after login
  1. Iterate through the remaining rows and calculate the 'C' values:
<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

Result

This approach will effectively populate the 'C' column with the desired calculated values:

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
2015-02-03  10  100  3000  250
Copy after login

The above is the detailed content of How to Calculate a Column Based on Previous Row Values in Pandas Using the `apply()` Function?. 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