【问题标题】:How to convert a dict inside a list to a DataFrame in python?python - 如何将列表中的dict转换为python中的DataFrame?
【发布时间】:2017-08-23 19:44:22
【问题描述】:

这里是 Python 初学者。我正在努力立即将我的listdicts 转储到pandas.DataFrame。我的数据具有以下结构。

a = {'Scores': {'s1': [{'Math': '95',
'Science': '74.5',                  
'English': '60.5'},                         
{'Math': '87.9',              
'Science': '97.3',                  
'English': '78.3'}],                        
's2': [{'Math': '67.2',       
'Science': '74.2',                        
'English': '89'}]}}  

我的pandas.Dataframe 列应该是科目“数学”、“科学”和“英语”,而行应该是分数。列是动态创建的,因此我不能明确提及要调用它的列名。我所需要的只是键 S1.... Sn.的值。

这是我迄今为止尝试过的:

b = a.pop('Scores')
c = list(b.values())
df = pd.DataFrame(c)

这将我的数据框显示为:

                                               0  \
0  {'Math': '95', 'Science': '74.5', 'English': '...
1  {'Math': '67.2', 'Science': '74.2', 'English':...

                                               1
0  {'Math': '87.9', 'Science': '97.3', 'English':...
1                                               None

相反,我正在寻找:

Math  Science  English
95    74.5     60.5
87.9  97.3     78.3
67.2  74.2     89

如果能得到任何帮助,我将不胜感激。

【问题讨论】:

    标签: python list pandas dictionary dataframe


    【解决方案1】:

    您可以在遍历字典的值后使用 sum。

    代码:

    import pandas as pd
    
    data = sum([x for x in a['Scores'].values()], [])
    print(pd.DataFrame(data, columns=['Math', 'Science', 'English']))
    

    测试数据:

    a = {'Scores': {'s1': [{'Math': '95',
                            'Science': '74.5',
                            'English': '60.5'},
                           {'Math': '87.9',
                            'Science': '97.3',
                            'English': '78.3'}],
                    's2': [{'Math': '67.2',
                            'Science': '74.2',
                            'English': '89'}]}}
    

    结果:

       Math Science English
    0  67.2    74.2      89
    1    95    74.5    60.5
    2  87.9    97.3    78.3
    

    【讨论】:

      【解决方案2】:

      您可以使用理解/生成器提取所有分数:

      >>> pd.DataFrame(s for k, v in a['Scores'].items() for s in v)
        English  Math Science
      0    60.5    95    74.5
      1    78.3  87.9    97.3
      2      89  67.2    74.2
      

      【讨论】:

        【解决方案3】:

        你必须自己apply

        pd.Series(a['Scores']).apply(pd.Series).stack().apply(pd.Series)
        
             English  Math Science
        s1 0    60.5    95    74.5
           1    78.3  87.9    97.3
        s2 0      89  67.2    74.2
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-14
          • 2020-10-23
          • 2019-06-24
          • 2021-11-06
          • 2020-07-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多