Python Forum
Pandas Dataframe conditional actions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pandas Dataframe conditional actions
#1
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
Reply
#2
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Assigning conditional values in Pandas Scott 3 796 Dec-19-2023, 03:10 AM
Last Post: Larz60+
  HTML Decoder pandas dataframe column mbrown009 3 1,027 Sep-29-2023, 05:56 PM
Last Post: deanhystad
  Use pandas to obtain cartesian product between a dataframe of int and equations? haihal 0 1,117 Jan-06-2023, 10:53 PM
Last Post: haihal
  xlswriter(pandas) and conditional format paul18fr 1 1,162 Aug-28-2022, 07:56 AM
Last Post: paul18fr
  Pandas Dataframe Filtering based on rows mvdlm 0 1,430 Apr-02-2022, 06:39 PM
Last Post: mvdlm
  Pandas dataframe: calculate metrics by year mcva 1 2,311 Mar-02-2022, 08:22 AM
Last Post: mcva
  Pandas dataframe comparing anto5 0 1,260 Jan-30-2022, 10:21 AM
Last Post: anto5
  PANDAS: DataFrame | Replace and others questions moduki1 2 1,794 Jan-10-2022, 07:19 PM
Last Post: moduki1
  PANDAS: DataFrame | Saving the wrong value moduki1 0 1,550 Jan-10-2022, 04:42 PM
Last Post: moduki1
  update values in one dataframe based on another dataframe - Pandas iliasb 2 9,253 Aug-14-2021, 12:38 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020