Detecting Value Crossing Between Columns In Pandas
Let's say I have the following dataframe: df = pd.DataFrame({'a': [10, 20, 30, 40, 50], 'b': [0, 10, 40, 45, 50]}, columns = ['a', 'b']) I would like to make a list of indices whe
Solution 1:
You can use the Series.shift
with Series.lt
which is "less than", same as <
and Series.ge
which is "greater than or equal" and is same as >=
:
mask = df['a'].shift().lt(df['b']) & df['a'].ge(df['b'])
# same as (df['A'].shift() < df['b']) & (df['a'] >= df['b'])
0False1False2False3False4True
dtype: bool
Notice, we don't have to specify astype(bool)
, pandas works with boolean indexing
and returns booleans
when defining conditions.
To get the indices
of the rows with True
, use:
idx = df[mask].index.tolist()
print(idx)
[4]
Post a Comment for "Detecting Value Crossing Between Columns In Pandas"