【问题标题】:Get dataframe from confusing dictionary data structure从令人困惑的字典数据结构中获取数据帧
【发布时间】:2020-06-21 19:59:02
【问题描述】:

我有一本像下面这样的字典:

    {1:            ds       yhat  yhat_lower  yhat_upper
30 2015-08-09  49.908927   31.632462   66.742083
31 2015-08-16  49.750056   34.065527   67.069122
32 2015-08-23  49.591185   32.620258   67.403908
33 2015-08-30  49.432314   32.257891   67.541757
34 2015-09-06  72.395618   55.612973   89.711030
35 2015-09-13  49.114572   32.199945   66.255518
36 2015-09-20  48.955701   30.759960   66.118051,
    2:            ds       yhat  yhat_lower  yhat_upper
30 2015-08-09  38.001931   23.583157   51.291784
31 2015-08-16  37.922999   25.370967   50.504328
32 2015-08-23  37.844068   23.743860   51.143868
33 2015-08-30  37.765136   24.903955   50.309284
34 2015-09-06  39.227773   25.089493   52.719935
35 2015-09-13  37.607273   24.370609   51.313454
36 2015-09-20  37.528341   23.395560   50.499454}

想要得到这样的输出数据帧

ProductCode    ds         yhat       yhat_lower  yhat_upper
  1           2015-08-09  49.908927   31.632462   66.742083
  1           2015-08-16  49.750056   34.065527   67.069122
  1           2015-08-23  49.591185   32.620258   67.403908
  1           2015-08-30  49.432314   32.257891   67.541757
  1           2015-09-06  72.395618   55.612973   89.711030
  1           2015-09-13  49.114572   32.199945   66.255518
  1           2015-09-20  48.955701   30.759960   66.118051,
  2           2015-08-09  38.001931   23.583157   51.291784
  2           2015-08-16  37.922999   25.370967   50.504328
  2           2015-08-23  37.844068   23.743860   51.143868
  2           2015-08-30  37.765136   24.903955   50.309284
  2           2015-09-06  39.227773   25.089493   52.719935
  2           2015-09-13  37.607273   24.370609   51.313454
  2           2015-09-20  37.528341   23.395560   50.499454

我的失败尝试: new_df = pd.DataFrame(df.items(), columns=['ProductCode', 'yhat']) 打印(new_df)

      ProdutCode    yhat

     0  1        ds yhat yhat_lower yhat_upp...
     1  2        ds yhat yhat_lower yhat_upp...

在字典中所有的 ds yhat yhat_lower 和 yhat_upper head 以及它们的值都被当作 dict.values()。如何将这些字母部分分隔为 Dataframe 列和数值部分是它们自己的列值?

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    让我们试试pd.concat

    yourdf=pd.concat(d).reset_index(level=0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      • 2013-09-22
      • 1970-01-01
      • 2019-09-05
      • 2011-10-13
      相关资源
      最近更新 更多