首页 > 解决方案 > 将带有字典子列表的字典转换为 pandas 数据框

问题描述

我有这个带有字典“dict”的代码:


import pandas as pd

dict = {
    '2000': [{'team': 'Manchester United', 'points': '91'}],
    '2001': [{'team': 'Manchester United', 'points': '80'}],
    '2002': [{'team': 'Arsenal', 'points': '87'}]
}

df = pd.DataFrame.from_dict(dict, orient='index')
print(df)

结果是:

                                                 0
2000  {'team': 'Manchester United', 'points': '91'}
2001  {'team': 'Manchester United', 'points': '80'}
2002            {'team': 'Arsenal', 'points': '87'}

但我想要的是:

        team                  points
2000    Manchester United     91
2001    Manchester United     80
2002    Arsenal               87

我想获得这个,而不是在 python 中使用循环,而是使用 pandas。谁能帮我吗?

提前致谢!

标签: pythonpandasdataframedictionary

解决方案


Tr这个。这将取决于您的数据有多大。


diction =  {
    '2000': [{'team': 'Manchester United', 'points': '91'}],
    '2001': [{'team': 'Manchester United', 'points': '80'}],
    '2002': [{'team': 'Arsenal', 'points': '87'}]
}
transformed_dict= {x:d for x,y in diction.items() for d in y }
df = pd.DataFrame(transformed_dict)
df.T

推荐阅读