Python 如何将非对称字典转换为数据帧
我正在使用上面的字典,并希望通过拆分lat和long值,然后复制它们以在新DF中创建对称来创建以下数据帧:Python 如何将非对称字典转换为数据帧,python,pandas,dataframe,dictionary,recursion,Python,Pandas,Dataframe,Dictionary,Recursion,我正在使用上面的字典,并希望通过拆分lat和long值,然后复制它们以在新DF中创建对称来创建以下数据帧: dict_circles = { 'radii': [1, 5, 10, 15], 'feature_group': [1, 5, 10, 15], 'lat_long': {'city1': [lat1, long1], 'city2': [lat2, long2] } } 据我所知,我需要
dict_circles = {
'radii': [1, 5, 10, 15],
'feature_group': [1, 5, 10, 15],
'lat_long': {'city1': [lat1, long1],
'city2': [lat2, long2]
}
}
据我所知,我需要一个递归[isinstance(data,type)或其他..]函数来访问嵌套在内部字典“lat_long”中的列表,可能还需要使用“pd.DataFrame.From_dict()”,可能还需要字典理解。我想不出解决办法。如果有更好的策略,请提供建议。这里有一种方法可以使用
dict\u circles
:
**radii** **feature_group** **lat** **long**
city1 1 1 lat1 long1
city2 1 1 lat2 long2
city1 5 5 lat1 long1
city2 5 5 lat2 long2
city1 10 10 lat1 long1
city2 10 10 lat2 long2
city1 15 15 lat1 long1
city2 15 15 lat2 long2
谢谢!这段代码就像一个符咒,更像是一个python。太棒了。@soka1228-如果答案满足您的需要,您可能想要-只需单击答案旁边的复选标记。此步骤是可选的,但建议执行。
import pandas as pd
# I multiplied each feature group by 10, to distinguish vs radii
dict_circles = {
'radii': [1, 5, 10, 15],
'feature_group': [10, 50, 100, 150],
'lat_long': {'city1': ['lat1', 'long1'],
'city2': ['lat2', 'long2']
}
}
# convert dict_circles (which is a nested dict) to list-of-tuples
tuples = [(city, r, fg, lat, lon)
for r, fg in zip(dict_circles['radii'], dict_circles['feature_group'])
for city, (lat,lon) in dict_circles['lat_long'].items()
]
# the list-of-tuples is compatible with the DataFrame constructor
df = pd.DataFrame(tuples,
columns=('city', 'radii', 'feature_group', 'lat', 'long'))
print(df)
city radii feature_group lat long
0 city1 1 10 lat1 long1
1 city2 1 10 lat2 long2
2 city1 5 50 lat1 long1
3 city2 5 50 lat2 long2
4 city1 10 100 lat1 long1
5 city2 10 100 lat2 long2
6 city1 15 150 lat1 long1
7 city2 15 150 lat2 long2