Skip to content
Advertisement

Pandas Dataframe into nested Dictionaries conversion in Python

I need a little help. I want to convert from dataframe into nested dictionaries.

    A   B    C
0   1   0    1.5
1   1   3,2  6.09
2   1   4    7.9
3   2   5    9.5
4   2   0    1.2
5   3   3    2.4

and i want to convert in this format:

dict={1:[{'0':1.5},{'3,2':6.09},{'4':7.9}],2:[{'5':9.5},{'0':1.2}],3:[{'3',2.4}]}

Advertisement

Answer

We can do groupby with agg dict items

d = df.set_index('B').groupby('A').agg(lambda x : [{k:v} for k, v in dict(x).items()])['C'].to_dict()
Out[574]: 
{1: [{'0': 1.5}, {'3,2': 6.09}, {'4': 7.9}],
 2: [{'5': 9.5}, {'0': 1.2}],
 3: [{'3': 2.4}]}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement