Pandas Dataframe conditional actions - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Pandas Dataframe conditional actions (/thread-14527.html) |
Pandas Dataframe conditional actions - tom1983 - Dec-04-2018 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: but what I really want is: 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 RE: Pandas Dataframe conditional actions - MAZambelli4353 - Dec-06-2018 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) |