1

我正在使用 tabula-py 从 PDF 中提取表格。但是在一些行多于一行的表中,但是在tabula-py中,单表行在DataFrame中被转换为多行。我在这里给出一个样本。

    Serial No.  Name    Type    Total
0   1   Easter         Multiple    19   
1   2   Costeri        Roundabout  16   
2   3   Zhiop            Tee       16   
3   4   Nesss           Cross      10   
4   5   Uoar Lhahara    Tee        10   
5   6   Trino Nishra (KX) Tee       9   
6   7   Old-FX Box      Cross       8
7   8   Gardeners    Roundabout     8   
8   9   Max Detter   Roundabout     7   
9   NaN Others (Asynco, NaN        NaN  
10  10  D+ E,           Cross       7   
11  NaN etc)            NaN        NaN  

如果您查看示例,您将看到 9、10 和 11 索引中的行实际上是单行。表格中有多行(pdf格式)。该表有 100 多行,并且至少有 12 个地方发生了这些问题。有些地方是连续 2 行,有些地方是连续 3 行。我们如何将这些行与索引值合并?

4

1 回答 1

2

你可以试试:

df['Serial No.'] = df['Serial No.'].bfill().ffill()
df['Total'] = df['Total'].astype(str).replace('nan', np.nan)

df_out = df.groupby('Serial No.', as_index=False).agg(lambda x: ''.join(x.dropna()))
df_out['Total'] = df_out['Total'].replace('', np.nan, regex=True).astype(float)

结果:

print(df_out)

   Serial No.                      Name        Type  Total
0         1.0                    Easter    Multiple   19.0
1         2.0                   Costeri  Roundabout   16.0
2         3.0                     Zhiop         Tee   16.0
3         4.0                     Nesss       Cross   10.0
4         5.0              Uoar Lhahara         Tee   10.0
5         6.0          Trino Nishra(KX)         Tee    9.0
6         7.0                Old-FX Box       Cross    8.0
7         8.0                 Gardeners  Roundabout    8.0
8         9.0                Max Detter  Roundabout    7.0
9        10.0  Others (Asynco,D+ E,etc)       Cross    7.0
于 2021-06-30T19:27:08.780 回答