Pandas数据帧到没有索引的json

时间:2015-02-18 18:04:15

标签: python json pandas

我正在尝试使用数据帧并将其转换为部分json格式。

这是我的数据框示例:

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

这是我想转换成的json格式:

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

注意这是一个dicts列表。我几乎在那里使用以下代码:

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

但是,该行还包括如下索引:

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

请注意,这是一个dicts的词典,并且还包括索引两次(在第一个词典中,在第二个词典中作为“id”!任何帮助都将受到赞赏。

4 个答案:

答案 0 :(得分:48)

您可以使用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]"}
]

答案 1 :(得分:1)

自 2017 年以来,有一个 index=False 选项。与 orient='split'orient='table' 一起使用。归功于对类似问题的回答:https://stackoverflow.com/a/59438648/1056563

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

答案 2 :(得分:0)

如果要使用Python dict (Python中等效的JSON对象)而不是JSON字符串:

import requests
import urllib.request
import random
from bs4 import BeautifulSoup as bs


url = 'https://goodlogo.com/top.250/n/250/interval/6'

sourcecode = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
plain_text = sourcecode.text
soup = bs(plain_text, 'html.parser')


path = 'C:/Users/roysu/Desktop/src_code/Python_projects/python/web_scrap/myPath/'


link = soup.select(".top_s3l")
for tag in link:
    my_images = tag.get('src')
    path_new = my_images.replace("/images/logos/small/", "")
    file_name = path+path_new

    full_name = 'https://goodlogo.com'+my_images
    sourcecode1 = requests.get(
        full_name, headers={'User-Agent': 'Mozilla/5.0'})
    file = open(file_name, "wb")
    file.write(sourcecode1.content)
    file.close()


link1 = soup.select(".top_s3")
for tag1 in link1:
    my_images1 = tag1.get('src')

    path_new1 = my_images1.replace("/images/logos/small/", "")
    file_name1 = path+path_new1

    full_name1 = 'https://goodlogo.com'+my_images1
    enter code here
    sourcecode1 = requests.get(
        full_name1, headers={'User-Agent': 'Mozilla/5.0'})
    file = open(file_name1, "wb")
    file.write(sourcecode1.content)
    file.close()

答案 3 :(得分:0)

还有另一种方式。

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