【问题标题】:Converting data in the dictionary into a dataframe with index in the rows将字典中的数据转换为行中具有索引的数据框
【发布时间】:2019-06-12 00:04:11
【问题描述】:

我有以下问题。给定字典 dict = { 'value_1': [12,25,30,45,60] , 'value_2': [ 15,21,31]} 将上述字典转换为数据框的更简单方法是什么,其中一列是两个键的项目的串联,另一列是每个项目的索引? 以下应该是输出 index 0 1 0 value_11 12 1 value_12 25 2 value_13 30 3 value_14 45 4 value_15 60 0 value_21 15 1 value_22 21 2 value_23 31

我采用的方法非常耗时。 我首先拿了这些物品并列出了清单。对于我为 i 运行 for 循环的索引,索引将是 'value_1'+str(i),然后将所有内容组合成一个数据框。有没有更简单的方法来做到这一点?

【问题讨论】:

    标签: python pandas indexing frame


    【解决方案1】:

    可能不是最快的,但你可以试试:

    pd.concat(pd.DataFrame([[f'{k}{i+1}', val] for i,val in enumerate(v)]) 
              for k,v in d.items() )
    

    输出:

              0   1
    0  value_11  12
    1  value_12  25
    2  value_13  30
    3  value_14  45
    4  value_15  60
    0  value_21  15
    1  value_22  21
    2  value_23  31
    

    【讨论】:

      【解决方案2】:

      IIUC 我们使用 Series 解压您的 dict ,然后使用 cumcount 添加新列

      s=pd.Series(d).apply(pd.Series).stack().reset_index(level=0)
      s['level_0']=s['level_0']+s.groupby('level_0').cumcount().add(1).astype(str)
      s
          level_0     0
      0  value_11  12.0
      1  value_12  25.0
      2  value_13  30.0
      3  value_14  45.0
      4  value_15  60.0
      0  value_21  15.0
      1  value_22  21.0
      2  value_23  31.0
      

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 2022-01-25
        • 2021-02-03
        • 2021-02-14
        • 2018-11-07
        • 2019-03-04
        • 2021-06-19
        • 2018-06-03
        • 2020-07-31
        相关资源
        最近更新 更多