2

I need help creating a new column on my dataframe

I have the following dataframe:

          OPEN    CLOSE
1      1.10074  1.10073
2      1.10073  1.10083
3      1.10083  1.10082
4      1.10082  1.10070
5      1.10071  1.10073
6      1.10073  1.10083
7      1.10083  1.10083
8      1.10083  1.10086
9      1.10088  1.10073
10     1.10073  1.10075

I would like to tag the values ​​in the 'CLOSE' column whenever greater or less than the previous

example exit:

          OPEN    CLOSE   TAG
1      1.10074  1.10073     ?   #anything can be placed
2      1.10073  1.10083     1   #value higher than previous
3      1.10083  1.10082     0
4      1.10082  1.10070     0
5      1.10071  1.10073     1   #value higher than previous
6      1.10073  1.10083     1   #value higher than previous
7      1.10083  1.10083     ?   #when equal anything can be placed
8      1.10083  1.10086     1   #value higher than previous
9      1.10088  1.10073     0
10     1.10073  1.10075     1   #value higher than previous

what would be the best way to do this? I tried with enumerate but I couldn't. Thank you for your help.

  • 1
    Does this answer your question? [Comparing previous row values in Pandas DataFrame](https://stackoverflow.com/questions/41399538/comparing-previous-row-values-in-pandas-dataframe) – AMC Jan 21 '20 at 01:58

2 Answers2

2

You can use .shift(n) where n represents the amount of prior rows to compare to:

(df['CLOSE'] > df['CLOSE'].shift(1)).astype(int)
realr
  • 3,652
  • 6
  • 23
  • 34
1

start with:

df['prev']=df['CLOSE'].shift(1)

result:

    OPEN    CLOSE   prev
1   1.10074 1.10073 NaN
2   1.10073 1.10083 1.10073
3   1.10083 1.10082 1.10083
4   1.10082 1.10070 1.10082
5   1.10071 1.10073 1.10070
6   1.10073 1.10083 1.10073
7   1.10083 1.10083 1.10083
8   1.10083 1.10086 1.10083
9   1.10088 1.10073 1.10086
10  1.10073 1.10075 1.10073

than add:

import numpy as np
df['TAG'] = np.where(df['CLOSE']-df['prev']>0,1,0)

result:

    OPEN    CLOSE   prev       TAG
1   1.10074 1.10073 NaN 0
2   1.10073 1.10083 1.10073    1
3   1.10083 1.10082 1.10083    0
4   1.10082 1.10070 1.10082    0
5   1.10071 1.10073 1.10070    1
6   1.10073 1.10083 1.10073    1
7   1.10083 1.10083 1.10083    0
8   1.10083 1.10086 1.10083    1
9   1.10088 1.10073 1.10086    0
10  1.10073 1.10075 1.10073    1

if you wish to improve in the event of equals you can do something like this:

df['TAG'] = np.where(df['CLOSE']-df['prev']>0,1,np.where(df['CLOSE']-df['prev']==0,'EQUALS',0))

desired result:

    OPEN    CLOSE   prev       TAG
1   1.10074 1.10073 NaN 0
2   1.10073 1.10083 1.10073    1
3   1.10083 1.10082 1.10083    0
4   1.10082 1.10070 1.10082    0
5   1.10071 1.10073 1.10070    1
6   1.10073 1.10083 1.10073    1
7   1.10083 1.10083 1.10083    EQUALS
8   1.10083 1.10086 1.10083    1
9   1.10088 1.10073 1.10086    0
10  1.10073 1.10075 1.10073    1
adhg
  • 10,437
  • 12
  • 58
  • 94