将字典转换为熊猫数据框

时间:2020-11-01 12:00:37

标签: python pandas dataframe dictionary

将以下字典转换为pandas数据框的最佳方法是什么?

以下给定的字典:

[{'answer': 'N', 'data': ('yello', 'big', 'first', 'marketing')},
 {'answer': 'Y', 'data': ('red', 'small', 'third', 'HR')}, ...
]

需要转换为以下数据框:

enter image description here

3 个答案:

答案 0 :(得分:4)

您可以这样做:

import pandas as pd

rows = [{'answer': 'N', 'data': ('yello', 'big', 'first', 'marketing')},
        {'answer': 'Y', 'data': ('red', 'small', 'third', 'HR')}
        ]

df = pd.DataFrame(data=[[d['answer'], *d['data']] for d in rows],
             columns=['answer', 'color', 'size', 'category', 'department'])

print(df)

输出

  answer  color   size category department
0      N  yello    big    first  marketing
1      Y    red  small    third         HR

答案 1 :(得分:0)

尝试一下:

d2=[{'answer':i['answer'], 'color':i['data'][0], 'size':i['data'][1], 'category':i['data'][2], 'department':i['data'][3]} for i in d]

df=pd.DataFrame(d2)

>>>print(df)

  answer  color   size category department
0      N  yello    big    first  marketing
1      Y    red  small    third         HR

答案 2 :(得分:0)

有趣的答案。使用pd.DataFrame.to_list

共享另一种方法
import pandas as pd

ls = [{'answer': 'N', 'data': ('yello', 'big', 'first', 'marketing')},
 {'answer': 'Y', 'data': ('red', 'small', 'third', 'HR')},
]
df = pd.DataFrame(ls)
df = pd.concat((df[['answer']], 
            pd.DataFrame(df['data'].to_list(), 
                         columns=['color','size', 'category', 'department']).reindex(df.index)),
           axis=1, join='inner')

输出:

    answer  color   size    category    department
0   N       yello   big     first       marketing
1   Y       red     small   third       HR