1

My dataframe is

  'col1' , 'col2'
    A    ,   89
    A    ,   232
    C    ,   545
    D    ,   998

and would like to export as follow :

{
  'A' : [ 89, 232 ],
  'C' : [545],
  'D' : [998]   
}

However, all the to_json does not fit this format (orient='records', ...). Is there a way to ouput like this ?

1 Answer 1

2

Use groupby for convert to list and then to_json:

json = df.groupby('col1')['col2'].apply(list).to_json()
print (json)
{"A":[89,232],"C":[545],"D":[998]}

Detail:

print (df.groupby('col1')['col2'].apply(list))
col1
A    [89, 232]
C        [545]
D        [998]
Name: col2, dtype: object
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.