Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

python - Problem with linear regression and summarize

I would like to create a plot of my linear regression model showing bike sales for each year summed up at one point, and not like now that there are two points separately.

This is my code:

from sklearn.linear_model import LinearRegression
from sklearn import datasets, linear_model

## Wzrost lub maleje zakup rowerow
## (Purchase of bicycles increases or decreases)
plot1 = df.groupby('Year')['Product_Category'].value_counts().rename('count').reset_index()

x = plot1['Year'].values.reshape(-1, 1)
y = plot1['count'].values.reshape(-1, 1)

# plot #
## linear ##
regr = linear_model.LinearRegression()
regr.fit(x, y)
y_pred = regr.predict(x_test)

#plot#
plt.scatter(x, y,  color='black')
plt.plot(x, y, color='blue', linewidth=3)

This is my plot:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As what I can understand from your example, this maybe a solution, replace value_counts by count.

Example data:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'Year': [ 2019, 2019, 2020, 2021], 'Product_Category': ['a', 'b', 'c', 'd']})
print(df)
   Year Product_Category
0  2019                a
1  2019                b
2  2020                c
3  2021                d

The count will return:

plot1 = df.groupby('Year')['Product_Category'].count().rename('count').reset_index()
print(plot1)

  Year  count
0  2019      2
1  2020      1
2  2021      1


plot1 = df.groupby('Year')['Product_Category'].count().rename('count').reset_index()
#x,y#
x = plot1['Year'].values.reshape(-1, 1)
y = plot1['count'].values.reshape(-1, 1)
# plot #

#plot#
plt.scatter(x, y,  color='black')
plt.plot(x, y, color='blue', linewidth=3)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...