给定一组(时间序列)数据,如何解释数据是递增/递减、不稳定、不变等。
Year  Revenue
1993     0.85
1994     0.99
1995     1.01
1996     1.12
1997     1.25
1998     1.36
1999     1.28
2000     1.44发布于 2017-03-21 15:32:35
你可以使用numpy.polyfit,你可以提供阶数作为拟合多项式的次数。
参考:numpy.polyfit documentation
import numpy as np
import pandas as pd
def trendline(data, order=1):
    coeffs = np.polyfit(data.index.values, list(data), order)
    slope = coeffs[-2]
    return float(slope)
#Sample Dataframe
revenue = [0.85, 0.99, 1.01, 1.12, 1.25, 1.36, 1.28, 1.44]
year = [1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000]
# check if values are exactly same
if (len(set(revenue))) <= 1:
    print(0)
else:
    df = pd.DataFrame({'year': year, 'revenue': revenue})
    slope = trendline(df['revenue'])
    print(slope)所以现在如果斜率的值是+ve,趋势是增加的,如果是0,趋势是恒定的,否则是下降的
在给定的数据中,斜率为0.0804761904762。因此,这一趋势正在增加
更新:趋势线失败的情况下,恰好是常量值,你可以添加自定义检查(len(set(revenue))) <= 1进行验证,如果是这种情况,返回0。
发布于 2017-03-21 15:28:32
如果您按'Year'对数据帧进行排序
df.sort_values('Year', inplace=True)然后,您可以观察pd.Series属性
df.Revenue.is_monotonic
df.Revenue.is_monotonic_decreasing
df.Revenue.is_monotonic_increasing
https://stackoverflow.com/questions/42920537
复制相似问题