我正在尝试从 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 错误。我有一些 year
和 sqft
的测试用例没有抛出错误并且可以确认 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/