【问题标题】:Appending tables generated from a loop附加从循环生成的表
【发布时间】:2021-07-14 05:47:03
【问题描述】:

我是这里的新 python 用户,我正在尝试将我使用 Camelot 从 pdf 中提取的数据附加在一起,但无法将它们连接在一起。

这是我的代码:

url = 'https://www.fhfa.gov/DataTools/Downloads/Documents/HPI/HPI_AT_Tables.pdf'

tables = camelot.read_pdf(url,flavor='stream', edge_tol = 500, pages = '1-end')

i = 0

while i in range(0,tables.n):
    header = tables[i].df.index[tables[i].df.iloc[:,0]=='Metropolitan Statistical Area'].to_list()
    header = str(header)[1:-1]
    header = (int(header))
    tables[i].df = tables[i].df.rename(columns = tables[i].df.iloc[header])
    tables[i].df = tables[i].df.drop(columns = {'': 'Blank'})

    print(tables[i].df)
    #appended_data.append(tables[i].df)
    
#if i > 0:
#    dfs = tables[i-1].append(tables[i], ignore_index = True)
#pass

    i = i + 1

任何帮助将不胜感激

【问题讨论】:

    标签: pandas loops pdf append


    【解决方案1】:

    您可以使用pandas.concat() 连接数据框列表。

    while i in range(0,tables.n):
        header = tables[i].df.index[tables[i].df.iloc[:,0]=='Metropolitan Statistical Area'].to_list()
        header = str(header)[1:-1]
        header = (int(header))
        tables[i].df = tables[i].df.rename(columns = tables[i].df.iloc[header])
        tables[i].df = tables[i].df.drop(columns = {'': 'Blank'})
    
    df_ = pd.concat([table.df for table in tables])
    

    【讨论】:

    • 哇,就是这么简单!非常感谢,干杯!
    • @BenSorensen 您也可以使用pd.concat(.., ignore_index=True) 忽略后面的数据帧索引。
    猜你喜欢
    • 2022-01-04
    • 2022-01-13
    • 1970-01-01
    • 2016-10-20
    • 2015-06-01
    相关资源
    最近更新 更多