【问题标题】:concatenate tables from loop getting error - InvalidIndexError: Reindexing only valid with uniquely valued Index objects从循环连接表得到错误 - InvalidIndexError:重新索引仅对具有唯一值的索引对象有效
【发布时间】:2021-07-18 01:42:06
【问题描述】:

我需要连接从循环创建的表。列中的名称重复,但它们讲述的是不同的故事,但由于某种原因,在运行此代码时出现错误:

InvalidIndexError: Reindexing only valid with uniquely valued Index objects

代码如下:

url = 'https://www.impactfees.com/publications%20pdf/2019survey.pdf'

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

i = 0


while i in range(0,tables.n):
    table_value = tables[i].df.loc[0,4]
    header = 1
    header = tables[i].df.iloc[header]
    tables[i].df = tables[i].df.rename(columns = header)
    
    nan_v = float("NaN")
    tables[i].df.replace('',nan_v,inplace = True) 
    tables[i].df.dropna(subset = ['Jurisdiction'], inplace = True)
    tables[i].df.replace(['Jurisdiction'], nan_v, inplace = True)
    tables[i].df.dropna(subset = ['Jurisdiction'], inplace = True)

#    Tot_col = tables[i].df.columns.get_loc('Total')
#    tables[i].df = tables[i].df.iloc[:,0:Tot_col+1]
    tables[i].df['report_name'] = table_value
    tables[i].df.loc[~tables[i].df.index.duplicated(keep = 'first')]
    i = i + 1

dfs = pd.concat([table.df for table in tables])

dfs

这是我得到的错误:

InvalidIndexError                         Traceback (most recent call last)
<ipython-input-133-2617eb5ae448> in <module>
     23     i = i + 1
     24 
---> 25 dfs = pd.concat([table.df for table in tables])
     26 
     27 

~\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy)
    296     )
    297 
--> 298     return op.get_result()
    299 
    300 

~\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in get_result(self)
    514                     obj_labels = obj.axes[1 - ax]
    515                     if not new_labels.equals(obj_labels):
--> 516                         indexers[ax] = obj_labels.get_indexer(new_labels)
    517 
    518                 mgrs_indexers.append((obj._mgr, indexers))

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_indexer(self, target, method, limit, tolerance)
   3169 
   3170         if not self.is_unique:
-> 3171             raise InvalidIndexError(
   3172                 "Reindexing only valid with uniquely valued Index objects"
   3173             )

InvalidIndexError: Reindexing only valid with uniquely valued Index objects

【问题讨论】:

  • 列不匹配。
  • @Ynjxsjmh 是对的,如果您查看 pdf,例如在您找到的表的第 2 页第 2 页的第 3 行,您还可以看到它们不匹配的位置和原因一个suspension extended indefinitely as of 3/21/19,它只将 5 列合并为 1。还有很多其他的。

标签: pandas dataframe loops concatenation python-camelot


【解决方案1】:
  • camelot 有问题。我必须修补 utils.py 以使用不同的 user-agent
  • 页面不完全一致,因此将 list 传递给 rename(columns=) 不起作用。你需要传递一个 dict
  • 保留了两个数据框 - 一个包含目标行,另一个包含排除行
  • 仍有不一致的列,例如排水公园
import pandas as pd
import camelot

url = 'https://www.impactfees.com/publications%20pdf/2019survey.pdf'
tables = camelot.read_pdf(url, flavor = 'stream', edge_tol = 500, pages = '4-end')

df = pd.DataFrame()
dfexc = pd.DataFrame()
for i in range(tables.n):
    dft = tables[i].df.rename(columns={i:v.replace("\n"," ") for i,v in tables[i].df.iloc[1].items() if v!=""})
    if " " in dft.columns[0]: 
        dft = dft.rename(columns={dft.columns[0]:dft.columns[0].split(" ")[0], 1:dft.columns[0].split(" ")[1]})
    m = (dft.State.str.len()!=2) | (dft.index < 2)

    dfexc = pd.concat([dfexc, tables[i].df.loc[m].assign(page=i)])
    df = pd.concat([df, dft.loc[~m].assign(page=i)])#.reset_index(drop=True)

【讨论】:

  • 嗨 Rob 但我只是不明白为什么 out 不会将不匹配的列添加到末尾,并且在根本没有任何内容的工作表上将其设为“NaN”。你不认为应该是这样吗?
  • @BenSorensen 这是一个偏好。在我使用 ETL 的 25 年中,我更喜欢将与数据模型匹配的源行和不匹配的源行分开。那些没有的可能需要额外的规则来放入数据模型或者可以是有效的排除(例如标题定义)
  • 如何为 Camelot 分配新的用户代理,我不知道该怎么做。我知道如何用 tabula 做到这一点,但我无法用 camelot 做到这一点。你能给我一些见解吗?
  • 我把它安装在一个 venv 中。我修补了 Camelot 的代码,以便在 utils.py 中使用不同的用户代理,您可以在 Camelot 包下找到该用户代理。没有办法将它作为参数传递...
  • 是的,我想通了...我最终使用 urllib 下载了 pdf,然后用 camelot 打开它...camelot 作为 pdf 阅读器和转换器非常方便。感谢您的帮助,祝您度过愉快的一周!
猜你喜欢
  • 1970-01-01
  • 2020-10-23
  • 2021-12-23
  • 1970-01-01
  • 2023-04-02
  • 2022-07-15
  • 2021-07-22
  • 2021-05-22
  • 2018-10-27
相关资源
最近更新 更多