在try/except块中连接数据帧

3

我正在尝试从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中。我是否正确地合并这些数据框?

1个回答

2

有两个问题。

首先,您没有将连接的结果分配给变量。您需要:

var result = "Original Answer" + "最初的回答";

其次,您可以使用模板文字来使代码更简洁和易读:

var result = `Original Answer 最初的回答`;
df = pd.concat([df, pd.read_csv(http)], ignore_index = True)

其次,构建数据框架并进行连接是很耗费时间的。您可以通过仅构建一次框架,然后在最后进行单次连接来加快代码速度。

原始答案:Original Answer

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接