【发布时间】:2019-06-08 04:50:23
【问题描述】:
我正在尝试将以下 dict 转换为数据框:
city_data = {
'San Francisco': {'x': [1, 2, 3], 'y': [4, 1, 2]},
'Montreal': {'x': [1, 2, 3], 'y': [2, 4, 5]},
'New York City': {'x': [1, 2, 3], 'y': [2, 2, 7]},
'Cincinnati': {'x': [1, 2, 3], 'y': [1, 0, 2]},
'Toronto': {'x': [1, 2, 3], 'y': [4, 7, 3]},
'Ottawa': {'x': [1, 2, 3], 'y': [2, 3, 3]}
}
这样数据框看起来像这样:
city | x | y
San Francisco | 1 | 4
San Francisco | 2 | 1
San Francisco | 3 | 2
...
使用我在这里找到的解决方案 Unfold a nested dictionary with lists into a pandas DataFrame 我试过了:
data = city_data
def unroll(data):
if isinstance(data, dict):
for key, value in data.items():
# Recursively unroll the next level and prepend the key to each row.
for row in unroll(value):
yield [key] + row
if isinstance(data, list):
# This is the bottom of the structure (defines exactly one row).
yield data
df = pd.DataFrame(list(unroll(nested_dict)))
df.rename(columns=lambda i: 'col{}'.format(i+1))
但是,我最终得到了这个结果:
【问题讨论】:
-
我的欺骗明确适用于this answer。
import json; df = pd.read_json(json.dumps(city_data), orient='index')带你到起点。 -
算了,问题比被骗更复杂。但我认为这与我提供链接的问题有关
标签: python pandas pydictionary