Home > database >  How to know if every subsequent value is greater than the preceding ones in a pandas column? Python
How to know if every subsequent value is greater than the preceding ones in a pandas column? Python

Time:08-06

Say I have the following df called df_trading_pair which contains the following data:

           Start Date  Open Price  High Price  Low Price  Close Price   Volume                End Date
0 2022-08-06 05:30:00      0.3738      0.3741     0.3737       0.3739  13767.0 2022-08-06 05:32:59.999
1 2022-08-06 05:33:00      0.3739      0.3742     0.3738       0.3741  28212.0 2022-08-06 05:35:59.999
2 2022-08-06 05:36:00      0.3740      0.3743     0.3739       0.3740  47274.0 2022-08-06 05:38:59.999
3 2022-08-06 05:39:00      0.3740      0.3740     0.3737       0.3739  55859.0 2022-08-06 05:41:59.999

After running df_trading_pair["Volume"], you get:

0    13767.0
1    28212.0
2    47274.0
3    55859.0
Name: Volume, dtype: float64

How can I know if every subsequent value is greater than the preceding ones in df_trading_pair["Volume"]

Initially I thought of coding something like this:

if df_trading_pair["Volume"][3] > df_trading_pair["Volume"][2] > df_trading_pair["Volume"][1] > f_trading_pair["Volume"][0]:

   print(True)

But that doesn't look very Pythonic

So I came here to learn a better approach to do that.

May I get some help here?

CodePudding user response:

Use:

df_trading_pair["Volume"].diff().iloc[1:].gt(0).all()

output: True

explanation:

(df_trading_pair["Volume"]
.diff()     # compute pairwise difference
.iloc[1:]   # remove first row
.gt(0)      # are the differences positive?
.all()      # are ALL differences positive?
)

numpy alternative:

a = df_trading_pair["Volume"].to_numpy()

(a[1:]>a[:-1]).all()
# True

CodePudding user response:

Another way using SHIFT

((df['Volume'] - df['Volume'].shift())[1:] > 0).all()

Or using DIFF

(df['Volume'].diff()[1:] > 0).all()
  • Related