I have data frame like
data = pd.DataFrame({'col1' :['A','A','A','B','B','C','C','C'], 'col2': ['13','15','17','11','15','12','21','23'], 'col3' : [3,5,8,7,2,5,1,3]},columns= ['col1', 'col2', 'col3'])
print(data)
col1 col2 col3
0 A 13 3
1 A 15 5
2 A 17 8
3 B 11 7
4 B 15 2
5 C 12 5
6 C 21 1
7 C 23 3
I want to convert this dataframe into like
[{"A": {"col2": ["13": 3,"15": 5,"17": 8]},"B": {"col2": ["11": 7,"15": 2]},"C": {"col2": ["12": 5,"21": 1,"23": 3]}}]
I tried using groupby by 'col1' then converting last two columns into dictionary but it not getting desired result.
Thank you for help.
You'll have to bite the bullet and use a lambda with a groupby statement.
Note lambda's aren't very efficient and this doesn't really seem like a logical / proper json structure.
but to answer your question.
data.groupby('col1')\
.apply(lambda x : {'col2' : dict(zip(x['col2'],x['col3']))}).to_dict()
{'A': {'col2': {'13': 3, '15': 5, '17': 8}},
'B': {'col2': {'11': 7, '15': 2}},
'C': {'col2': {'12': 5, '21': 1, '23': 3}}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.