簡體   English   中英

如何將列表中的字典轉換為python中的DataFrame?

[英]How to convert a dict inside a list to a DataFrame in python?

Python初學者在這里。 我正在努力將我的dicts list立即轉儲到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列應該是'Math','Science'和'English'主題,行應該是分數。 這些列是動態創建的,因此我無法明確提及要調用的列名稱。 我需要的只是鍵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

我將不勝感激。

您可以在對dict的值進行迭代之后再使用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

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

>>> 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

你必須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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM