最小二乗法による単回帰分析でよければ、 numpy.linalg.lstsq() でも良いかと。
https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html
Python
1import pandas as pd
2import numpy as np
3import matplotlib.pyplot as plt
4
5data = pd.DataFrame(
6 [
7 [100, 200, 300, 400, 500],
8 [100, 200, 300, 400, 500],
9 [100, 200, 200, 300, 300],
10 [500, 400, 300, 200, 100],
11 [500, 400, 300, 200, 100]
12 ],
13 columns=['1月', '2月', '3月', '4月', '5月'],
14 index=['A101', 'A102', 'A103', 'A104', 'A105'])
15
16A = np.vstack([range(data.shape[1]), np.ones(data.shape[1])]).T
17data = data.join(data.apply(lambda d: pd.Series(np.linalg.lstsq(A, d, rcond=None)[0], index=['w1', 'w0']), axis=1))
18print(data)
19# 1月 2月 3月 4月 5月 w1 w0
20#A101 100 200 300 400 500 100.0 100.0
21#A102 100 200 300 400 500 100.0 100.0
22#A103 100 200 200 300 300 50.0 120.0
23#A104 500 400 300 200 100 -100.0 500.0
24#A105 500 400 300 200 100 -100.0 500.0
25
26# 一応確認
27fig, axs = plt.subplots(1, 5, figsize=[12,3])
28for (name, d), ax in zip(data.iterrows(), axs):
29 x = np.arange(5)
30 f = lambda p: d.w0 + d.w1 * p
31 ax.plot(x, d[:5], '.')
32 ax.plot(x, f(x), '-')
33 ax.set_title(name)
34plt.show()
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/28 01:37