我在 pandas 数据框中有以下数据(见下文)。
我想将其转换为如下所示的字典:
my_dict = {
'AB': {
'city1': (0.000000, 0.000000),
'city2' : (0.100000, 0.200000),
'city3' : (0.200000, 0.400000)
}
'BC': {
'city4': (0.300000, 0.600000),
'city5' : (0.400000, 0.800000),
}
}
我知道 pandas 的 to_dict()
方法,但无法强制它执行此操作。
iso city lat lng
0 AB city1 0.000000 0.000000
1 AB city2 0.100000 0.200000
2 AB city3 0.200000 0.400000
3 BC city4 0.300000 0.600000
4 BC city5 0.400000 0.800000
最佳答案
您可以首先通过 zip
lat
和 lng
创建列 zipped
,然后通过 groupby
双 to_dict
:
#python 3 need convert to list
df['zipped'] = list(zip(df.lat, df.lng))
print (df)
iso city lat lng zipped
0 AB city1 0.0 0.0 (0.0, 0.0)
1 AB city2 0.1 0.2 (0.1, 0.2)
2 AB city3 0.2 0.4 (0.2, 0.4)
3 BC city4 0.3 0.6 (0.3, 0.6)
4 BC city5 0.4 0.8 (0.4, 0.8)
d = df.groupby('iso').apply(lambda x: x.set_index('city')['zipped'].to_dict()).to_dict()
print (d)
{'AB': {'city3': (0.20000000000000001, 0.40000000000000002),
'city1': (0.0, 0.0),
'city2': (0.10000000000000001, 0.20000000000000001)},
'BC': {'city4': (0.29999999999999999, 0.59999999999999998),
'city5': (0.40000000000000002, 0.80000000000000004)}}
关于python - 来自 pandas 数据框的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38307855/