【发布时间】:2019-12-01 06:41:18
【问题描述】:
这是我烦人的嵌套字典:
"data": [
{
'type': 'a',
'id': '3',
'attributes': {'name': 'Alexander',
'address': 'Ree 25',
'postalCode': '3019 VM',
'place': 'Amsterdam',
'company': 'Pizza BV',
'phoneNumbers': [{'description': 'general', 'phoneNumber': '+31104136911'}],
'locationCode': 'DURTM',
'website': 'http://www.pizzabv.nl',
'primaryEmail': 'info@pizzabv.nl',
'secondaryEmail': '',
'geoLocation': {'type': 'Point',
'coordinates': [16.309702884655767, 31.879930329139634]
}
},
'relationships': [],
'links': {'self': 'www.homepage.nl'
}
},
{
'type': 'b',
'id': '7',
'attributes': {'name': 'Sam',
'address': 'Zee 15',
'postalCode': '2019 AM',
'place': 'Groningen',
'company': 'Salami BV',
'phoneNumbers': [{'description': 'specific', 'phoneNumber': '+31404136121'}],
'locationCode': 'SWSTM',
'website': 'http://www.salamibv.nl',
'primaryEmail': 'info@salamibv.nl',
'secondaryEmail': '',
'geoLocation': {'type': 'Point',
'coordinates': [18.309702884655767, 34.879930329139634]
}
},
'relationships': [],
'links': {'self': 'www.homepage.nl'
}
}
]
这就是我想要的数据框:
type | id | name | address | postalCode | ... | type | coordinates | relationships | links
... ... ... ... ... ... ... ... ... ...
因此,必须将不同的底层词典上移一层。首先必须删除属性,并且必须将基础值上移一层。
另外,description 和 phoneNumber 必须上移一层,然后 phoneNumbers 才能删除。
此外,关于 type 和 id 的所有信息都应放在一行中。
我不知道该怎么做。我尝试了以下几种方法:
terminals = pd.DataFrame.from_dict(data, orient='columns')
terminals.reset_index(level=0, inplace=True)
terminals.head()
但这在 Pandas 数据框的一个单元格中为我提供了完整的字典。
希望有人能帮帮我。
【问题讨论】:
标签: python pandas dataframe dictionary nested