python - 来自 pandas 数据框的嵌套字典

标签 python pandas dictionary nested

我在 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 latlng 创建列 zipped,然后通过 groupbyto_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/

相关文章:

python - 在python中连接多个数组

python - 如何将多个数据框附加到一个数据框中

python - str.contains pandas 返回 'str' 对象没有属性 'contains'

python - 索引和列上的 pandas df.rename 并不总是有效

c# - 如何使用带有字典列表的 asp.net 转发器?

python - 编译python扩展模块时链接错误

python - Pandas Multiindex - 对组执行操作

c# - 在 C# 中序列化和反序列化 V.Large 字典

python - 如何删除嵌套容器中的重复条目

python - pygame,如何获取图形的坐标?