python-计算 pandas 系列趋势线的斜率

是否有一种惯用的方法来获取DataFrame列中线性趋势线拟合值的斜率?使用DateTime索引对数据进行索引.

最佳答案

应该这样做:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(100, 5), pd.date_range('2012-01-01', periods=100))

def trend(df):
    df = df.copy().sort_index()
    dates = df.index.to_julian_date().values[:, None]
    x = np.concatenate([np.ones_like(dates), dates], axis=1)
    y = df.values
    return pd.DataFrame(np.linalg.pinv(x.T.dot(x)).dot(x.T).dot(y).T,
                        df.columns, ['Constant', 'Trend'])


trend(df)

enter image description here

使用与上面相同的df作为索引:

df_sample = pd.DataFrame((df.index.to_julian_date()* 10 2)np.random.rand(100)* 1e3,
                        df.index)

coef = trend(df_sample)
df_sample['trend'] = (coef.iloc[0, 1] * df_sample.index.to_julian_date() + coef.iloc[0, 0])
df_sample.plot(style=['.', '-'])

enter image description here