Reputation: 9348
A list of monthly sales until November, I want to know if the sales trend is upward.
Definition of upward: each monthly sales is greater or at least equal to previous month's.
This question is similar to Python: Finding a trend in a set of numbers, but much simpler - only looking the list of numbers.
What I have now is, to check them one by one (in a list). If one month satisfies the condition, it adds an "ok" to a new list. When total number of "ok" equals to 10. The original list of numbers are upward.
import pandas as pd
df_a = pd.DataFrame([['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov'],
[278,342,476,500,559,594,687,739,917,940,982]]).T
df_a.columns = ["Month", "Sales"]
sales_a = df_a['Sales'].tolist()
ok_a = []
for num, a in enumerate(sales_a):
if sales_a[num] >= sales_a[num-1]:
ok_a.append("ok")
if ok_a.count("ok") == 10:
print ("df_a is uptrend.")
What's the smarter way to do it? Thank you.
Upvotes: 1
Views: 248
Reputation: 25239
Pandas Series has attribute is_monotonic
to check on monotonic increasing. Don't need to sort or do anything fancy.
print(df_a.Sales.is_monotonic)
Out[94]: True
if df_a.Sales.is_monotonic:
print('df_a is uptrend')
Output:
df_a is uptrend
Upvotes: 4
Reputation: 674
A simpler way would be to check
if(sales_a == sorted(sales_a)):
print("uptrend")
At the cost of increase in final complexity by a log
factor.
Upvotes: 1
Reputation: 789
You can use the diff
and period
method on pandas
df_a['Sales_diff'] = df_a['Sales'].diff(periods=1)
df_a['OK'] = df_a['Sales_diff'] >= 0
df_a
Upvotes: 1
Reputation: 8033
you can do as below
if df_a['Sales'].diff().fillna(0).ge(0).all():
print ("df_a is uptrend.")
else:
print ("df_a is NOT a uptrend.")
Upvotes: 2