I want to get slopes of dataset in the dataframe (either using linear regression model or sk-learn model).
df1:
A B C D
0 15 25 55 100
1 15.5 25.5 56 101
2 14.8 24.5 54.2 99.8
3 15.5 25.5 55.5 102
4 16 26 57 108
I want to get slopes of each dolumn ('A', 'B', 'C', 'D') in the form of pd.Series. Can you help me on this? Thank you.
The output I want is something like below (I used just dummy numbers, not real slopes!):
slopes:
A 2.5
B 2.8
C 3.1
D 3.3
I believe this does it, it's a simple linear regression with numpy
import numpy as np
slopes = df.apply(lambda x: np.polyfit(df.index, x, 1)[0])
>>> slopes
A 0.20
B 0.20
C 0.35
D 1.70
And if you want to visualize the data and the fitted slopes:
for i in df.columns:
plt.scatter(df.index, df[i], label=i)
plt.plot(np.polyval(np.polyfit(df.index, df[i], 1), df.index))
plt.legend()
plt.show()