【问题标题】:Convert list type dictionary to pandas dataframe - python将列表类型字典转换为熊猫数据框 - python
【发布时间】:2022-01-06 06:23:21
【问题描述】:

我想转换有两行的字典。值在第一行,键在第二行。

这是我的字典:

{'data': [['1', 'Male', ['a,b,c'], 'USA'],['2', 'Male', ['r,g,e'], 'JAPAN'],['3', 'Female', ['f,r,b'], 'UK']],
 'columns': ['id', 'gender', 'array_userid' ,'location']}

我想将其转换为如下所示的 pandas 数据框:

     id     gender   array_userid   location
0    1      Male     ['a,b,c']      USA
1    2      Male     ['r,g,e']      JAPAN
3    3      Female   ['f,r,b']      UK

【问题讨论】:

    标签: python pandas list dictionary


    【解决方案1】:

    DataFrame 构造函数与字典的选择值一起使用:

    d = {'data': [['1', 'Male', ['a,b,c'], 'USA'],['2', 'Male', ['r,g,e'], 'JAPAN'],['3', 'Female', ['f,r,b'], 'UK']],
     'columns': ['id', 'gender', 'array_userid' ,'location']}
    

    df = pd.DataFrame(data=d['data'], columns=d['columns'])
    print (df)
      id  gender array_userid location
    0  1    Male      [a,b,c]      USA
    1  2    Male      [r,g,e]    JAPAN
    2  3  Female      [f,r,b]       UK
    

    【讨论】:

      猜你喜欢
      • 2017-12-12
      • 2018-11-25
      • 1970-01-01
      • 2016-09-06
      • 2019-07-18
      • 2018-07-14
      • 2019-05-07
      • 2017-10-02
      相关资源
      最近更新 更多