首页 > 解决方案 > pandas:将奇怪的字典类型的数据更改为数据框

问题描述

我正在处理采用奇怪形式的预测结果,并且我没有找到将其转换为可操作的数据框的方法。

我听说过 itertools,但它似乎对我没有用,除非我用错了。

这是我尝试做的事情:

forecast = {}
def holts(i):
    fit1 = ExponentialSmoothing(new_df.iloc[:,i], trend=True).fit()
    prediction_interval = fit1.get_forecast(steps=12).summary_frame(alpha=0.10) #make predictions

    df = pd.DataFrame(prediction_interval).reset_index()#put in dataframe
   
   

    forecast[i] = df # append results to dictionary
    print(forecast)
    return forecast

这会返回一个像这样的字典:

{0: 100121      index      mean   mean_se  mean_ci_lower  mean_ci_upper
0      2020-07-31 -1.422683  7.346106     -13.505952      10.660585
1      2020-08-31 -1.875716  7.346106     -13.958985      10.207552
2      2020-09-30 -2.328749  7.346106     -14.412019       9.754520, 
1: 100140      index       mean     mean_se  mean_ci_lower  mean_ci_upper
0      2020-07-31   2.161468   50.224646     -80.450724      84.773659
1      2020-08-31  10.597280   55.244561     -80.271936     101.466496
2      2020-09-30  19.033093   65.139972     -88.112625     126.178811 }

我想要实现的是:

    Id       Date    ...  mean_ci_lower  mean_ci_upper
100121 2020-07-31    ...       7.346106     -13.505952
100121 2020-08-31    ...     -13.958985     -13.505952
100140 2020-07-31    ...       7.346106     -13.505952
100140 2020-08-31    ...     -13.958985     -13.505952

我对熊猫很差,但我觉得我越来越近了,但我找不到处理字典奇怪标题的方法,我尝试过使用 itertools 但实际上没有成功。

顺便说一句,这旨在存储超过 1000 Id ,任何人都可以提出一种更有效的方法来存储预测结果吗?

更新:正如我尝试过的评论中所建议的那样pd.concat,虽然这更接近它消除了 df 中的 Id 值:

      index      mean   mean_se  mean_ci_lower  mean_ci_upper
0 0      2020-07-31 -1.422683  7.346106     -13.505952      10.660585
  1      2020-08-31 -1.875716  7.346106     -13.958985      10.207552
  2      2020-09-30 -2.328749  7.346106     -14.412019       9.754520
      index       mean     mean_se  mean_ci_lower  mean_ci_upper
1 0      2020-07-31   2.161468   50.224646     -80.450724      84.773659
  1      2020-08-31  10.597280   55.244561     -80.271936     101.466496
  2      2020-09-30  19.033093   65.139972     -88.112625     126.178811 

标签: pythonpandasdataframedictionary

解决方案


我相信idcolumns.nameindex.name

forecast = {}
def holts(i):
    fit1 = ExponentialSmoothing(new_df.iloc[:,i], trend=True).fit()
    prediction_interval = fit1.get_forecast(steps=12).summary_frame(alpha=0.10)

    df = pd.DataFrame(prediction_interval)
    print (df.columns.name)
    print (df.index.name)

    forecast[df.columns.name] = df 
    #or 
    #forecast[df.index.name] = df 
    print(forecast)
    
df = pd.concat(forecast)

推荐阅读