2015-02-18 12 views
20

Ich versuche, einen Datenrahmen zu nehmen und ihn in ein spezielles JSON-Format umzuwandeln.Pandas Datenframe zu Json ohne Index

Hier ist mein Datenrahmen Beispiel:

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

Hier ist das JSON-Format Ich mag würde in verwandeln:

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

Hinweis es dich um eine Liste von dicts ist. Ich habe es fast da mit dem folgenden Code:

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

jedoch diese Zeile enthält auch der Index wie folgt aus:

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

Hinweis dies ein dict von dicts ist und schließt auch den Index zweimal (in der ersten dict und als "id" in der zweiten dict! Jede Hilfe würde geschätzt.

Antwort

34

können Sie verwenden 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]"} 
] 
+2

Das ist so einfach. Ich liebe Pandas ... und du! Vielen Dank! –

+0

Wenn Sie überhaupt keinen Index möchten, entfernen Sie einfach den "reset_index()" Teil. – Aaron

Verwandte Themen