首页 > 解决方案 > 将 python 列表解压缩到数据框中

问题描述

我对 python 还很陌生,我遇到了函数返回的数据类型的问题。我有两个功能准备和模型

def Prepare(Inputdf):

    x0 = list(range(e ,s+1 ,-1))
    X = Inputdf[x0] 
    Y = Inputdf['y0']

    return [X,Y]

# Linear Model
def Model(Inputdf, X, Y):

    #Train
    X = sm.add_constant(X)
    lmodel = sm.OLS(Y, X).fit()
    summ = lmodel.summary()

    #Test
    x1 = list(range(e-1 ,s ,-1))
    A = Inputdf[x1]
    A = sm.add_constant(A)

    newcol = lmodel.predict(A)
    newdf = pd.concat([Inputdf, newcol], axis=1)

    return [newdf]

它们在下面的循环中被调用。该函数返回一个列表,但我不确定如何将输出转换为数据框

forecast = []
for i in wh:
    TrainFinal = TrainInput[TrainInput['column'].isin([i])]
    TestFinal = TestInput[TestInput['column'].isin([i])]

    Modelresult = Model(TestFinal, *Prepare(TrainFinal))
    forecast.append(Modelresult)

    print (forecast)

输出看起来像这样

[[                   country    y1          0
6990  United Arab Emirates  42.0  24.314137
...                    ...   ...        ...
7426  United Arab Emirates  12.0   8.281969
[71 rows x 3 columns]], 
[                   country    y1          0
8338  United Arab Emirates  97.0  66.740899
...                    ...   ...        ...
8696  United Arab Emirates   8.0  12.884740
[67 rows x 3 columns]], 
[    country    y1          0
284   Chile   6.0  16.672239
...   ...     ...     ...
374   Chile   5.0  13.534690
[67 rows x 3 columns]]

标签: pythonpandaslistdataframe

解决方案


我发现我做错了什么。我刚刚删除了“模型函数”中返回的数据框前面的括号

return [newdf] -> return newdf

然后我连接结果而不是附加它们,然后我重置索引以获得最终输出:)

forecast = pd.concat(Modelresult)
forecast.reset_index(drop=True, inplace=True)

推荐阅读