Home > database >  Applying a function to each couple of elements of a column in a pandas data frame
Applying a function to each couple of elements of a column in a pandas data frame

Time:02-07

I have the need to create a new column of a pandas data frame applying a function to each couple of consecutive elements.The first element if the new column has to be a nan. Let's assume that the function is the sum of the elements divided by 3. Here's an example to clarify what I need:

a b new_column
1 2 nan
3 4 2
5 5 3

the operation is on column b: first is nan, 2 = (2 4) / 3 == f(2,4), 3 = (4 5) / 3 == f(4,5)

Can anyone help me? Thank you really much

CodePudding user response:

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
    )
)
  •  Tags:  
  • Related