【问题标题】:Is there a way to obtain all rows/data from paginated json file into pandas dataframe有没有办法从分页的json文件中获取所有行/数据到pandas数据框中
【发布时间】:2022-01-11 13:39:29
【问题描述】:

已编辑:

这是我的步骤:

url = "https://ted.europa.eu/api/v2.0/notices/search?&q=TD%3D%5B3%5D&reverseOrder=true&scope=3&sortField=PD"

# get data from url 
response = requests.get(url)

# return the json data, and read the output dict keys
data = response.json()
data

我已经从一个 api 获得了一个 json 文件:

{'took': 205, 
 total': 1703997,
'results': [{'AA': '1',
'AC': '2',
'BI': [],
'CY': 'MK',
'DI': '1046/2018',
'TY': '1'},
{'AA': '6',
'AC': '1',
'BI': [],
'CY': 'RS',
'DI': 'CODE_OTHERS',
'TY': '1'},
{'AA': '5',
'AC': '1',
'BI': [],
'CY': 'BE',
'DI': '1046/2018',
'TY': '1'},
...
#read the output dict keys
data.keys()

当我将其转换为 pd df

df = pd.DataFrame(data["results"])

dict_keys(['took', 'total', 'results'])

# create dataframe from key of interest
df = pd.DataFrame(data["results"])
df.head()

这按预期返回了数据帧...

# count number of rows
len(df.index)

1000

但是,我预计总共是 1703997。

我还在思考如何解决这个问题????

知道我该怎么做吗?

【问题讨论】:

  • 您的 API 应该能够将页码作为参数。在while循环中,存储页面n的100个结果并递增n直到返回的json为空。 (或循环for n in range(result['total']//100)
  • 嗨 Tranbi,你能更详细地介绍一下 while 循环吗?谢谢
  • 您应该首先描述如何获取这些数据。对下一页重复该过程,直到结果为空。
  • 嗨,我在最近的编辑中详细介绍了我的步骤。请看一看。

标签: python json pandas api pyspark


【解决方案1】:

您应该在 API 请求中指定页面。不幸的是,API Doc doesn't seem to be available 还没有。
但是,根据Github 上的这个示例,您应该能够使用pageNum= 获取任何页面。
您应该能够使用以下内容将所有行附加到 df

url = "https://ted.europa.eu/api/v2.0/notices/search?&q=TD%3D%5B3%5D&reverseOrder=true&scope=3&sortField=PD"
response = requests.get(url)
data = response.json()
df = pd.DataFrame()
i = 1
while "results" in data.keys():
  df_page = pd.DataFrame(data["results"])
  # print(df_page.head()) # uncomment to see page #i as df
  df = df.append(df_page, ignore_index=True)
  i+=1
  response = requests.get(f'{url}&pageNum={i}')
  data = response.json()

阅读所有页面可能需要一段时间,所以请耐心等待 ;-)

编辑:

在您的示例中,代码将循环 1700 多次,然后才能获得响应 {'errorCode': 400, 'message': "The requested page number doesn't exist."}。我不知道您的内存/服务器是否可以处理那么多。 您可能希望将结果分成几个块...

【讨论】:

  • 谢谢。但是您是否设法提取任何数据?我昨天跑了几个小时,什么也没发生。
  • 我用更多细节编辑了我的答案(并更改了循环条件以避免KeyError)。试试while i < 5,应该会得到前 4000 个结果
  • 太棒了!这行得通。谢谢
猜你喜欢
  • 2020-06-29
  • 2011-07-20
  • 1970-01-01
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
相关资源
最近更新 更多