Home > Software design >  Create a Boolean column based on condition which involves value from a column of the current row and
Create a Boolean column based on condition which involves value from a column of the current row and

Time:01-06

I want to add a Boolean column to this Dataframe.

                          date    open    high     low   close  volume
1912 2023-01-05 09:15:00 05:30  641.80  644.30  626.35  628.60  615758
1913 2023-01-05 10:15:00 05:30  628.60  634.50  624.15  628.25  313480
1914 2023-01-05 11:15:00 05:30  627.80  633.45  627.40  632.80  193937
1915 2023-01-05 12:15:00 05:30  632.70  636.05  630.80  634.65  223713
1916 2023-01-05 13:15:00 05:30  634.65  635.00  629.45  634.90  224242
1917 2023-01-05 14:15:00 05:30  634.80  637.90  633.35  635.85  310906
1918 2023-01-05 15:15:00 05:30  635.90  637.35  633.50  633.55  101989

Boolean column should show True if the 'close' value of the row is greater than the 'close' value of the previous row, else it should be false.

how do I do that?

CodePudding user response:

You can use .shift(1) to compare with the previous row

df['compare'] = (df['close'] > df['close'].shift(1))
df

                          date    open    high     low   close  volume  compare
1912 2023-01-05 09:15:00 05:30  641.80  644.30  626.35  628.60  615758    False
1913 2023-01-05 10:15:00 05:30  628.60  634.50  624.15  628.25  313480    False
1914 2023-01-05 11:15:00 05:30  627.80  633.45  627.40  632.80  193937     True
1915 2023-01-05 12:15:00 05:30  632.70  636.05  630.80  634.65  223713     True
1916 2023-01-05 13:15:00 05:30  634.65  635.00  629.45  634.90  224242     True
1917 2023-01-05 14:15:00 05:30  634.80  637.90  633.35  635.85  310906     True
1918 2023-01-05 15:15:00 05:30  635.90  637.35  633.50  633.55  101989    False
  • Related