Dec-04-2018, 08:25 PM
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:
Any help would be highly appreciated.
Thanks in advance!
Tom
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