applying a function to each couple of elements of a column in a pandas data frame

I believe this solution should now give you the desired result:

# We are going to assign a new column
df = df.assign(
    # based on a function that we will apply
    new_column=df.apply(
        # If our row index is not 0: --> if row.name !=0
        # we take the value of column["b"] --> row["b]
        # we add the value located at the current row index -1 --> df["b"].iat[row.name -1]
        # then we divide by 3 without rest --> //3
        lambda row: (row["b"] + df["b"].iat[row.name - 1])//3 if row.name != 0 else "", axis=1
    )
)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top