【问题标题】:How to convert pandas df to dictionary with lists nested in the list?如何将 pandas df 转换为列表嵌套在列表中的字典?
【发布时间】:2020-09-11 21:28:31
【问题描述】:

我最近开始使用 python,现在我正在处理 API 请求。我需要将数据框转换为嵌套在列表中的列表字典。

如何转换 df:

data = {'x':  ['15.0', '42.2','43.4','89.0','45.8'],
        'y': ['10.1', '42.3','43.5','5.0','45.9']
         }

df = pd.DataFrame (data, columns = ['x','y'])

到嵌套在列表中的列表字典

{
  "Points": [
    [15.0, 10.1],    [42.2, 42.3],    [43.4, 43.5],    [89.0, 5.0],    [45.8, 45.9]
  ]
}

我尝试使用 df.to_dict 和 list 作为 orient 参数,但结果是 2 个长的 x 和 y 列表,而不是许多对列表。

对于python用户来说可能是微不足道的问题,提前感谢帮助!

【问题讨论】:

    标签: python json pandas dictionary


    【解决方案1】:

    你可以这样做:-

    res = {'Points' : [[row['x'], row['y']] for i, row in df.iterrows()]}
    print(res)
    

    输出:-

    {'Points': [['15.0', '10.1'], ['42.2', '42.3'], ['43.4', '43.5'], ['89.0', '5.0'], ['45.8', '45.9']]}
    
    【解决方案2】:

    通过DataFrame.to_numpy将值转换为numpy数组,然后列表:

    d = {"Points":df.to_numpy().tolist()}
    #if there is more columns
    #d = {"Points":df[['x','y']].to_numpy().tolist()}
    print (d)
    {'Points': [['15.0', '10.1'], ['42.2', '42.3'], 
                ['43.4', '43.5'], ['89.0', '5.0'], ['45.8', '45.9']]}
    

    【讨论】:

      【解决方案3】:

      给你:

      output = {}
      for i, row in df.iterrows():
          output['Points'] = [[row['x'], row['y']]
      
      print(output)
      

      【讨论】:

      猜你喜欢
      • 2021-04-27
      • 2019-12-31
      • 2018-10-26
      • 1970-01-01
      • 2019-05-27
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多