python - Nested dictionary from pandas data frame -
i have following data (see below) in pandas data frame.
i'd covert dict looks this:
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), } }
i aware of pandas' to_dict()
method have been unable coerce perform this.
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
you can first create column zipped
zip
lat
, lng
, groupby
double to_dict
:
#python 3 need convert 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)}}
Comments
Post a Comment