Skip to main content
 首页 » 编程设计

python之来自 Pandas 数据框的嵌套字典

2024年10月17日8yjmyzz

我在 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)}}