Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
How to get slopes of data in pandas dataframe in Python?

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
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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()
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Virtual assistant