48

I'm trying to take a dataframe and transform it into a particular json format.

Here's my dataframe example:

DataFrame name: Stops
id    location
0     [50, 50]
1     [60, 60]
2     [70, 70]
3     [80, 80]

Here's the json format I'd like to transform into:

"stops":
[
{
    "id": 1,
    "location": [50, 50]
},
{
    "id": 2,
    "location": [60, 60]
},
... (and so on)
]

Notice it's a list of dicts. I have it nearly there with the following code:

df.reset_index().to_json(orient='index)

However, that line also includes the index like this:

"stops":
{
"0":
    {
        "id": 0,
        "location": [50, 50]
    },
"1":
    {
        "id": 1,
        "location": [60, 60]
    },
... (and so on)
}

Notice this is a dict of dicts and also includes the index twice (in the first dict and as the "id" in the second dict! Any help would be appreciated.

1
  • Maybe the behavior changed? I get ValueError: too many values to unpack (expected 2) Commented Mar 1, 2021 at 18:37

4 Answers 4

90

You can use orient='records'

print df.reset_index().to_json(orient='records')

[
     {"id":0,"location":"[50, 50]"},
     {"id":1,"location":"[60, 60]"},
     {"id":2,"location":"[70, 70]"},
     {"id":3,"location":"[80, 80]"}
]
Sign up to request clarification or add additional context in comments.

3 Comments

That is so simple. I love pandas ... and you! Thanks!
If you don't want index at all, just remove "reset_index()" part.
Found this in accident.
6

Since 2017 there is an index=False option. Use it with orient='split' or orient='table'. Credit to this answer on a similar question: https://stackoverflow.com/a/59438648/1056563

    dfj = json.loads(df.to_json(orient='table',index=False))

Comments

3

If you want a Python dict (the JSON-object equivalent in python) not a JSON string:

df.to_dict(orient='records')

Comments

2

There is another way as well.

df_dict=df.reset_index().to_dict(orient='index')
df_vals=list(df_dict.values())

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.