0

I have a pandas dataframe and want to convert it to json format.

import pandas as pd
df = pd.DataFrame({'A': [1,2,3,4], 'B': [5,6,7,8]})
df.to_json()

'{"A":{"0":1,"1":2,"2":3,"3":4},"B":{"0":5,"1":6,"2":7,"3":8}}'

The json string I need is like below:

'{"A":[1,2,3,4], "B":[5,6,7,8]}'

How can I get this json string from pandas dataframe? Thanks a lot.

2 Answers 2

1

You can use to_dict() with orient='list' and consider the string representation of the output.

>>> str(df.to_dict(orient='list'))
"{'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8]}"
Sign up to request clarification or add additional context in comments.

Comments

0

Did you tried to put the argument index=False:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html

index:bool, default True Whether to include the index values in the JSON string. Not including the index (index=False) is only supported when orient is ‘split’ or ‘table’.

New in version 0.23.0.

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.