连接try/b中的数据帧

2024-04-24 14:48:26 发布

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

我正在尝试从API中提取数据,如果成功,则将结果连接到一个大数据帧中。下面是一个代码示例

df = pd.DataFrame()
year = 2000
while year < 2018:
    sqft = 1000
    while sqft < 1500:
        #will include buildHttp code if helpful to this problem
        http = buildHttp(sqft,year)
        try:
            tempDf = pd.read_csv(http)
        except:
            print("No properties matching year or sqft")
            sqft = sqft + 11
        else:
            pd.concat([df, pd.read_csv(http)], ignore_index = True)
            sqft = sqft + 11
    year = year + 1

buildHttp是一个函数,它构建了一个字符串,我可以将该字符串传递给API来尝试提取数据。我们不能保证某个楼盘已经以给定的平方英尺或在给定的年份售出,如果是这样,我们将抛出一个EmptyDataFrame错误。我有一些yearsqft的测试用例,它们没有抛出错误,并且可以确认buildHttp确实构建了适当的http,以便pd.read_csv(http)成功地提取数据。只有成功拉取的数据帧在完成后才不会出现在df中。我要正确组合这些数据帧吗?你知道吗


Tags: csv数据字符串代码apihttp示例df
1条回答
网友
1楼 · 发布于 2024-04-24 14:48:26

两件事。你知道吗

第一,你没有把连接的结果赋给一个变量。你想要什么

df = pd.concat([df, pd.read_csv(http)], ignore_index = True)

第二,构造数据帧和进行级联是昂贵的。只需构造一次帧,然后在最后执行一次串联,就可以加快代码的速度。你知道吗

frames = list()
year = 2000
while year < 2018:
    sqft = 1000
    while sqft < 1500:
        #will include buildHttp code if helpful to this problem
        http = buildHttp(sqft,year)
        try:
            df = pd.read_csv(http)
        except:
            print("No properties matching year or sqft")
        else:
            frames.append(df)
        finally:
            sqft = sqft + 11
   year = year + 1
df = pd.concat(frames, ignore_index=True)

相关问题 更多 >