edd
edd

Reputation: 291

How can I get the value of the previous row in a Dataframe to change the current row value (dynamically, not with a static value)

I would like to know if there's a pythonic way of accomplishing the following:

The goal is to add the column UpDown to this Dataframe

             Close  Diff  UpDown
Date                            
2019-11-14  148.06  0.75       0
2019-11-15  149.97  1.91       1
2019-11-18  150.34  0.37       2
2019-11-19  150.39  0.05       3
2019-11-20  149.62 -0.77      -1
2019-11-21  149.48 -0.14      -2
2019-11-22  149.59  0.11       1
2019-11-25  151.23  1.64       2

The UpDown column logic is the following:

I have tried using np.where() , .iterrows() and .shift() but couldn't find a way to do it

Upvotes: 0

Views: 66

Answers (1)

CDJB
CDJB

Reputation: 14506

Depends what you mean by pythonic - here is a solution that iterates over each row. Assuming we have our DataFrame as follows:

>>> df
             Close  Diff
2019-11-14  148.06  0.75
2019-11-15  149.97  1.91
2019-11-18  150.34  0.37
2019-11-19  150.39  0.05
2019-11-20  149.62 -0.77
2019-11-21  149.48 -0.14
2019-11-22  149.59  0.11
2019-11-25  151.23  1.64

then we can do the following:

df['UpDown'] = 0

for i, index in enumerate(df.index[1:]):
    if df.loc[index, 'Diff'] > 0:
        if df.loc[df.index[i], 'Diff'] > 0:
            df.loc[index, 'UpDown'] = df.loc[df.index[i], 'UpDown'] + 1
        else:
            df.loc[index, 'UpDown'] = 1
    else:
        if df.loc[df.index[i], 'Diff'] > 0:
            df.loc[index, 'UpDown'] = -1
        else:
            df.loc[index, 'UpDown'] = df.loc[df.index[i], 'UpDown'] - 1

Output:

>>> df
             Close  Diff  UpDown
2019-11-14  148.06  0.75       0
2019-11-15  149.97  1.91       1
2019-11-18  150.34  0.37       2
2019-11-19  150.39  0.05       3
2019-11-20  149.62 -0.77      -1
2019-11-21  149.48 -0.14      -2
2019-11-22  149.59  0.11       1
2019-11-25  151.23  1.64       2

Upvotes: 1

Related Questions