加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-在try / except块中串联数据帧

发布时间:2020-12-17 17:41:53 所属栏目:Python 来源:网络整理
导读:我正在尝试从API中提取数据,如果成功,则将结果串联到一个大数据框中.这是代码示例 df = pd.DataFrame()year = 2000while year 2018: sqft = 1000 while sqft 1500: #will include buildHttp code if helpful to this problem http = buildHttp(sqft,year) tr

我正在尝试从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,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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读