I need a little help. I want to convert from dataframe into nested dictionaries.
JavaScript
x
8
1
A B C
2
0 1 0 1.5
3
1 1 3,2 6.09
4
2 1 4 7.9
5
3 2 5 9.5
6
4 2 0 1.2
7
5 3 3 2.4
8
and i want to convert in this format:
JavaScript
1
2
1
dict={1:[{'0':1.5},{'3,2':6.09},{'4':7.9}],2:[{'5':9.5},{'0':1.2}],3:[{'3',2.4}]}
2
Advertisement
Answer
We can do groupby
with agg
dict
items
JavaScript
1
6
1
d = df.set_index('B').groupby('A').agg(lambda x : [{k:v} for k, v in dict(x).items()])['C'].to_dict()
2
Out[574]:
3
{1: [{'0': 1.5}, {'3,2': 6.09}, {'4': 7.9}],
4
2: [{'5': 9.5}, {'0': 1.2}],
5
3: [{'3': 2.4}]}
6