当我将数据保存到csv文件时,仅保存ID为103的记录,而ID为101和102的记录不可用。

import pandas as pd
import requests as rq

for vehicleList in range(101, 103):
    vehicleList = vehicleList + 1
    x = str(vehicleList)

    r = rq.get('https://api.tfl.gov.uk/vehicle/' + x + '/arrivals')
    r = r.text
    df = pd.read_json(r)

    df.to_csv('filename.csv')

最佳答案

保存之前,您需要连接数据。例如:

import pandas as pd
import requests as rq

temp = pd.DataFrame()
df = pd.DataFrame()

for vehicleList in range(101, 103):
    vehicleList = vehicleList + 1
    x = str(vehicleList)
    r = rq.get('https://api.tfl.gov.uk/vehicle/' + x + '/arrivals')
    r = r.text
    temp = pd.read_json(r)

    # some identifier here
    temp['Type'] = x

    # concat
    df = pd.concat([df, temp]).reset_index(drop=True)

df.to_csv('filename.csv')


您为每个循环temp分配一个临时DataFrame,然后添加一个唯一的ID表示组temp['Type'],然后连接到df。循环完成后,您将保存df及其所有迭代。

关于python - 如何在python(pandas)中保存数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59295095/

10-12 22:20