Python Forum
Pandas referring to result of a previous row
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pandas referring to result of a previous row
#1
Star 
Hi people,

Would really appreciate if you help me with something.
You know in Excel when you apply a formula on a cell and then drag it down so every row would be dependent on the result of the cell right above it?

So I need to do it in Python somehow.

I found a solution, but it's not working on my training set. Please advise!
Thanks alot for your help (=

I know with .shift() I can refer to a previous cell if they are not in the same column, .rolling() is providing good, but limited options. Also I cannot use cumulative functions, cause the result will differ depending on other columns' output.

I think my best shot is going for .apply()

df = pd.DataFrame([{'a': 15, 'b': 15, 'Cash': 5}, {'a': 20, 'b': 10, 'Cash': 7}, {'a': 25, 'b': 30, 'Cash': 9}])

def div(x):    
    last_row_id = x.name - 1 
    
    if x.name == 0:
        x['Cash'] = 1       
    else:      
        x['Cash'] = df['Cash'][last_row_id] + 1    
    return x

df.apply(div,axis=1)
What I get from it:
Output:
Cash a b 0 1 15 15 1 2 20 10 2 3 25 30
BUT as soon as I apply this logic to a bigger database, it stops working. Here is my problem:

test = result.copy()
test.reset_index(inplace=True)

def div(x):
    
    last_row_id = x.name - 1
    
    if x.name == 0:
        x['Cash']= 1
    else:
        x['Cash'] = test['Cash'][last_row_id] + 1
    
    return x

test = test.apply(div,axis=1)
test
Cash is supposed to go like 1,2,3,4,5, but it's not.

Output:
Cash QQQ 0 1 157.611725 1 1 159.143173 2 1 159.421616 3 1 161.022705 4 1 161.649200 5 1 161.659149
Reply
#2
SOLVED.

I used "for i, data in df.iterrows()" method
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Referring to a specific element in Pandas Dataframe Helmi 2 3,169 Mar-17-2019, 09:12 PM
Last Post: Helmi

Forum Jump:

User Panel Messages

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