【问题标题】:Issue with nested loop and df.append嵌套循环和 df.append 的问题
【发布时间】: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


【解决方案1】:

你的 for 循环的第一行有一个错误:

df[(df['country']== country)&(df['city']== city)]

有几件事。首先,这里没有赋值 - 您只是陈述过滤后的数据帧,但没有将其存储在变量中,因此在您的计算后期,您每次都在对整个数据集进行回归。

其次,如果您要执行df = df[<filters>],您仍然会遇到问题,因为您每次都会缩小数据帧。

您要做的是将过滤后的数据框存储为新变量,然后将其用于以后的计算:

df2 = df[(df['country']== country)&(df['city']== city)]
y = df2["total_customer"]
y = y.dropna()
x = df2[["total_purchase","total_items"]]
x = x.dropna()
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-17
    • 2016-06-23
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    相关资源
    最近更新 更多