Home > OS >  Pandas Dataframe into nested Dictionaries conversion in Python
Pandas Dataframe into nested Dictionaries conversion in Python

Time:03-08

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}]}

CodePudding user response:

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}]}

CodePudding user response:

This will give you a dictionary, remember dict is a key work in python so you have to use other variable name instead of dict. Here I used dict1.

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

CodePudding user response:

pretty similar to this solution:

df = df.set_index('B').groupby('A').apply(lambda x: [x['C'].to_dict()]).to_dict()

print(df)
'''
{1: [{'0': 1.5, '3,2': 6.09, '4': 7.9}],
 2: [{'5': 9.5, '0': 1.2}],
 3: [{'3': 2.4}]}
  • Related