如何使用pandas合并这些数据帧?

2024-10-03 00:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须对一个API进行多次调用,并将每次调用的结果合并到一个单一的数据帧中。他们有相同的钥匙,我可以做一次,但当我试图合并第三个,什么都没有发生。我可能也不是用最有效的方法

我最初尝试使用for循环来实现这一点,但出于实验目的,我尝试手动实现(每次更改5000个参数)。呼叫限制是5000,所以我一次只能做这么多记录。我知道我的一些变量名可能对它们所代表的内容描述不准确(“JSONString等”),但请耐心听我说

我将不包括在我的电话下面的网址,但它是准确的


#First call, gets the necessary values out of the API and successfully turns them into a dataframe

params = urllib.parse.urlencode({
    # Request parameters
    'limit': 5000,
})

categoriesJSON = s.get(url, headers=headers)
categoriesJSONString = categoriesJSON.json()
categoriesDf = pandas.DataFrame(categoriesJSONString['value'])


#Second call, gets the necessary values out of the API and successfully turns them into a dataframe and then appends that dataframe to the original dataframe successfully

params = urllib.parse.urlencode({
    # Request parameters
    'limit': 5000,
    'offset': 5000
    })

categoriesJSON = s.get(url, headers=headers)
categoriesJSONString = categoriesJSON.json()
newCategoriesDf = pandas.DataFrame(categoriesJSONString['value'])
categoriesDf.append(newCategoriesDf, ignore_index = True)

#Third, gets the necessary values out of the API and turns them into a dataframe and then appends that dataframe to the original dataframe unsuccessfully

params = urllib.parse.urlencode({
    # Request parameters
    'limit': 5000,
    'offset': 10000
    })

categoriesJSON = s.get(url, headers=headers)
categoriesJSONString = categoriesJSON.json()
newCategoriesDf = pandas.DataFrame(categoriesJSONString['value'])
categoriesDf.append(newCategoriesDf, ignore_index = True)

在第二次调用之后,我的数据帧是10000行长,但是在第三次调用之后,我的数据帧仍然是10000行长。什么阻止它长15000?我知道我有超过10000行的数据要获取


Tags: andofthe数据apidataframeoutheaders
2条回答

append返回追加的df,您需要将最后一行更改为:

categoriesDf = categoriesDf.append(newCategoriesDf, ignore_index = True)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html

Append返回一个新的数据帧,现有的数据帧不会更新

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html

像这样更新目标

download = pd.DataFrame(data = 1, index = [1], columns = ['Data'])
x = download
x = x.append(download, ignore_index=True)
x = x.append(download, ignore_index=True)
x = x.append(download, ignore_index=True)

相关问题 更多 >