Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

data transformation from pandas to json

I have a dataframe df:

d = {'col1': [1, 2,0,55,12,3], 'col3': ['A','A','A','B','B','B'] } 
 df = pd.DataFrame(data=d)
 df 

 col1        col3
0   1           A
1   2           A
2   0           A
3   55          B
4   12          B
6   3           B

and want to build a Json from it, as the results looks like this :

json_result = { 'A' : [1,2,0], 'B': [55,12,3] }

basically, I would like for each group of the col3 to affect an array of its corresponding values from the dataframe

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Aggregate list and then use Series.to_json:

print (df.groupby('col3')['col1'].agg(list).to_json())
{"A":[1,2,0],"B":[55,12,3]}

or if need dictionary use Series.to_dict:

print (df.groupby('col3')['col1'].agg(list).to_dict())
{'A': [1, 2, 0], 'B': [55, 12, 3]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading