Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas dataframe to json without index

I'm trying to take a dataframe and transform it into a partcular 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.

like image 343
Eric Miller Avatar asked Feb 18 '15 18:02

Eric Miller


People also ask

How do I get rid of pandas indexing?

Dropping a Pandas Index Column Using reset_index The most straightforward way to drop a Pandas dataframe index is to use the Pandas . reset_index() method. By default, the method will only reset the index, forcing values from 0 - len(df)-1 as the index.

Is pandas good for JSON?

Pandas read_json()This API from Pandas helps to read JSON data and works great for already flattened data like we have in our Example 1. You can download the JSON from here. Just reading the JSON converted it into a flat table below.

What is Orient in JSON?

orient: strIndication of expected JSON string format. Compatible JSON strings can be produced by to_json() with a corresponding orient value. The set of possible orients is: 'split' : dict like {index -> [index], columns -> [columns], data -> [values]} 'records' : list like [{column -> value}, ... , {column -> value}]


1 Answers

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]"} ] 
like image 116
Roman Pekar Avatar answered Sep 18 '22 09:09

Roman Pekar