Reputation: 521
Lets say that we have these columns in a df:
A B C
0 1 0 1
1 2 2 2
2 3 4 4
3 4 6 6
4 5 8 8
I know that I can check that every specific columns with monotonic_increasing like that
df['A'].is_monotonic_increasing.
I was wondering if there is a way to check/validate that the monotonic_increasing has a specific step. Let me explain. I would like for example to check that df['A']
is monotonic_increasing with step 1, the df['B']
is monotonic_increasing with step 2.
Is there a way to check that out ?
Upvotes: 0
Views: 521
Reputation: 2786
One liner to get all columns at once:
df.diff().iloc[1] * (df.diff().nunique() == 1)
Output:
A 1.0
B 2.0
C 0.0
Name: 1, dtype: float64
Output is the step size, or 0 if not monotonic increasing.
Upvotes: 0
Reputation: 150785
I don't think there's a function for that. We can build a two-line function:
def step_incr(series, step=1):
tmp = np.arange(len(series)) * step
return series.eq(series.iloc[0]+tmp).all()
step_incr(df['A'], step=1)
# True
step_incr(df['B'], step=1)
# False
Another way to check is looking at the values of differences:
def is_step(series):
uniques = series.diff().iloc[1:].unique()
if len(uniques) == 1:
return True, uniques[0]
return False, None
is_step(df['A'])
# (True, 1.0)
is_step(df['B'])
# (True, 2.0)
is_step(df['C'])
# (False, None)
Upvotes: 2