python - 在 try/except block 中连接数据帧

标签 python pandas

我正在尝试从 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 中。我要正确组合这些数据框吗?

最佳答案

两件事。

第一,您没有将连接的结果分配给变量。你想要

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)

关于python - 在 try/except block 中连接数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55657529/

相关文章:

python - Panda python 文本文件处理成 xlsx

python - 从 Google AppEngine 中的 blobstore 下载 zip 存档

python - 简单的Python字符串代码\解码脚本问题

python - 解析字典中的文本并分成键和值

python - Django 和 Django CMS 错误

python - Pandas 数据帧 col 转换为 timedelta 以使用重新采样

python - 使用 MultiIndex 时如何将此 Pandas 列类型保留为日期时间?

python - 大量按钮和智能检查被检查

python - 设置多索引系列的多个层

python - datetime.timestamp 在 pandas apply 和 dataframe 选择中返回不同的值