Changing values with conditional and function in pandas/python

Viewed 22

I have a dataframe, as per the table below A. I want to create a table with the values ​​of table B.

I would like to compare the next value in the row with the previous value in table A.

If the next value in the row is EQUAL to the previous value in the row, apply the function (value*3) to the next value(j).

If the next value is LESS than the previous one, we keep the same values.

If the next value is HIGHER than the previous one, we keep the same values.

TABLE A:

Bird1 Bird2 Bird3
100 50 200
100 40 100
100 40 100
80 80 200

The result should be as per the table below. How to implement this code in python?

TABLE B:

Bird1 Bird2 Bird3
100 50 200
300 40 100
900 120 300
80 80 200
1 Answers

Try:

df_out = df.apply(
    lambda x: [
        v := x[0],
        *(v := v * 3 if a - b == 0 else (v := b) for a, b in zip(x, x[1:])),
    ]
)
print(df_out)

Prints:

   Bird1  Bird2  Bird3
0    100     50    200
1    300     40    100
2    900    120    300
3     80     80    200
Related