简体   繁体   中英

Compare Values of a Pandas Dataframe in Python

I have a dataframe with open, high, low, close prices of a stock and I would create a new column called NewColumn that will be filled by checking in the close column if the 1st value is greater or not than the 2nd one and the 3rd than the 4th and the 5th than the 6th and so on till the end. Thanks in advance

    Date                open    high    low     close   NewColumn
0   2022-07-26 07:25:00 35.700  35.765  35.690  35.755
1   2022-07-26 07:30:00 35.755  35.760  35.690  35.695
2   2022-07-26 07:35:00 35.695  35.695  35.600  35.660
3   2022-07-26 07:40:00 35.660  35.710  35.585  35.600
4   2022-07-26 07:45:00 35.600  35.730  35.590  35.675
5   2022-07-26 07:50:00 35.675  35.715  35.545  35.600
6   2022-07-26 07:55:00 35.600  35.705  35.570  35.620
7   2022-07-26 08:00:00 35.620  35.695  35.595  35.640
8   2022-07-26 08:05:00 35.640  35.795  35.620  35.635
9   2022-07-26 08:10:00 35.635  35.675  35.545  35.555

...
...

You can use pandas.Series.shift :

df['NewColumn'] =  df['close'].gt(df['close'].shift(-1))

# Output:

print(df)

   Date                        open    high     low   close  NewColumn
0     0  2022-07-26 07:25:00 35.700  35.765  35.690  35.755       True
1     1  2022-07-26 07:30:00 35.755  35.760  35.690  35.695       True
2     2  2022-07-26 07:35:00 35.695  35.695  35.600  35.660       True
3     3  2022-07-26 07:40:00 35.660  35.710  35.585  35.600      False
4     4  2022-07-26 07:45:00 35.600  35.730  35.590  35.675       True
5     5  2022-07-26 07:50:00 35.675  35.715  35.545  35.600      False
6     6  2022-07-26 07:55:00 35.600  35.705  35.570  35.620      False
7     7  2022-07-26 08:00:00 35.620  35.695  35.595  35.640       True
8     8  2022-07-26 08:05:00 35.640  35.795  35.620  35.635       True
9     9  2022-07-26 08:10:00 35.635  35.675  35.545  35.555      False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM