Python Pandas 数据框到 json 没有索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28590663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas dataframe to json without index
提问by Eric Miller
I'm trying to take a dataframe and transform it into a partcular json format.
我正在尝试获取一个数据框并将其转换为特定的 json 格式。
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:
这是我想转换成的 json 格式:
"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)
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.
请注意,这是一个 dict 的 dict 并且还包括两次索引(在第一个 dict 中,并作为第二个 dict 中的“id”!任何帮助将不胜感激。
采纳答案by Roman Pekar
You can use orient='records'
您可以使用 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]"}
]