【问题标题】:expanding a row by splitting it into existing columns通过将行拆分为现有列来扩展行
【发布时间】:2021-05-07 11:11:30
【问题描述】:

我已经使用 tabula-py 命令从 pdf 中读取表格,代码如下:

table = tabula.read_pdf(files[0],pages = 'all',multiple_tables = True, stream = True)

有时来自两列的值会合并为一列(由单个空格分隔)。例如:

col0 col1 col2 col3 col4 col5 col6 col7
a1 b1 c1 d1 e1 f1 g1 h1 NA NA
a2 b2 c2 d2 e2 f2 g2 h2

如何将值重新调整到正确的列中,以获得:

col0 col1 col2 col3 col4 col5 col6 col7
a1 b1 c1 d1 e1 f1 g1 h1
a2 b2 c2 d2 e2 f2 g2 h2

【问题讨论】:

    标签: pandas dataframe split reshape


    【解决方案1】:

    你可以试试

    table = tabula.read_pdf(files[0],pages = 'all',multiple_tables = True,guess = False, stream = True)
    

    【讨论】:

      【解决方案2】:
      • 以空格分隔输出
      • 替换第 1 步中引用的字符串
      • 以空格分隔回读
      import io
      df = pd.read_csv(io.StringIO("""col0    col1    col2    col3    col4    col5    col6    col7
      a1  b1 c1   d1  e1 f1   g1  h1  NA  NA
      a2  b2  c2  d2  e2  f2  g2  h2"""), sep="\t")
      
      df = pd.read_csv(io.StringIO(df.to_csv(sep=" ").replace("\"", "")), sep="\s+")
      
      

      输出

      col0 col1 col2 col3 col4 col5 col6 col7
        a1   b1   c1   d1   e1   f1   g1   h1
        a2   b2   c2   d2   e2   f2   g2   h2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-20
        相关资源
        最近更新 更多