Python Forum

Full Version: Pandas Dataframe conditional actions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey there,

I have a simple Pandas Dataframe where I want if the condition is met (A is smaller than A of the line above)take the value of C from the line before being the actual value for C:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A' : [1,2,3,4,3,2,1],'B' : [1,2,3,4,3,2,1]})
df['C'] = df['A'] * df['B']
df.loc[df.A < df.A.shift(1), 'C'] = df['C'].shift(1)

print(df)
this gives me:

Output:
A B C 0 1 1 1.0 1 2 2 4.0 2 3 3 9.0 3 4 4 16.0 4 3 3 16.0 5 2 2 9.0 6 1 1 4.0
but what I really want is:

Output:
A B C 0 1 1 1.0 1 2 2 4.0 2 3 3 9.0 3 4 4 16.0 4 3 3 16.0 #A is getting smaller so we use C from the line above 5 2 2 16.0 #A is getting smaller again so we use C from the line above (again 16) 6 1 1 16.0 #A is getting smaller again so we use C from the line above (again 16)
the code I am using is unfortunately not doing what I want, it gives me the value from the line above, but only once.

Any help would be highly appreciated.


Thanks in advance!

Tom
df = pd.DataFrame({'A': [1, 2, 3, 4, 3, 2, 1], 'B': [1, 2, 3, 4, 3, 2, 1]})
df['C'] = df['A'] * df['B']

for n in range(len(df['C']) - 1):
    if df['C'][n] > df['C'][n + 1]:
        df['C'][n+1] = df['C'][n]
    else:
        pass
print(df)