【问题标题】:Nested dictionary from pandas data frame来自熊猫数据框的嵌套字典
【发布时间】:2016-11-13 10:54:28
【问题描述】:

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

【问题讨论】:

    标签: python pandas dictionary nested


    【解决方案1】:

    您可以先通过zip latlng 创建列zipped,然后使用双to_dict 创建groupby

    #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)}}
    

    【讨论】:

    • 我可能想在这里使用df['zipped'] = df.apply(lambda r: (r.lat, r.lng), axis=1)...
    猜你喜欢
    • 2021-02-15
    • 2019-03-02
    • 2023-03-23
    • 2018-04-14
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    相关资源
    最近更新 更多