简体   繁体   中英

Convert dictionary with sub-list of dictionaries into pandas dataframe

I have this code with a dictionary "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)

The result is:

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

But what I want is:

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

I would like to obtain this, without using loops in python, and by using pandas. Can anyone help me out?

Thanks in advance!

Tr this. This would depend on how large your data is.


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM