【发布时间】:2021-01-10 05:48:38
【问题描述】:
早上好,
我有以下数据集(由于主要数据集是机密的,所以编造了这个):
country city total_customer total_purchase total_items
France Paris 2355231 7848589 84454
Germany Berlin 3211551 5646545 84564
我想为每个国家和城市组合运行线性回归,并将其输出为最终的 pandas 数据框,如下所示:
country city coef1 coef2 intercept
France Paris -0.294942 258.471387 -625.582231
Germany Berlin 1.987 422.4554 454.645
到目前为止,我编写了以下代码(我的数据集很小,最多 10k 行,所以我不太担心性能):
import pandas as pd
from sklearn import linear_model
import statsmodels.api as sm
countries = df["country"].unique()
cities = df["city"].unique()
df_results = pd.DataFrame([], columns=['country','city','coef1','coef2','intercept'])
for country in countries:
for city in cities:
df[(df['country']== country)&(df['city']== city)]
y = df["total_customer"]
y = y.dropna()
x = df[["total_purchase","total_items"]]
x = x.dropna()
regr = linear_model.LinearRegression()
if df.empty:
continue
else:
regr.fit(x, y)
coef1 = regr.coef_[0]
coef2 = regr.coef_[1]
intercept = regr.intercept_
df_results = df_results.append({'country':country,'city':city,'coef1':coef1,'coef2':coef2,'intercept':intercept}, ignore_index=True)
输出如下:
df_results
country city coef1 coef2 intercept
0 France Paris -0.294942 258.471387 -625.582231
1 Germany Berlin -0.294942 258.471387 -625.582231
看起来 coef1、coef2 和拦截的结果将是单个输出,而不是每个线性回归运行的输出,我似乎无法修复它,所以如果有人能在此启发我,将不胜感激,谢谢!
【问题讨论】:
-
在我看来你正在适应整个 df,照顾你的
for city in cities你没有将你的 df 分配回任何东西。
标签: python pandas loops scikit-learn regression