使用Python從PDF文件中提取數(shù)據(jù)
前言
數(shù)據(jù)是數(shù)據(jù)科學(xué)中任何分析的關(guān)鍵,大多數(shù)分析中最常用的數(shù)據(jù)集類型是存儲在逗號分隔值(csv)表中的干凈數(shù)據(jù)。然而,由于可移植文檔格式(pdf)文件是最常用的文件格式之一,因此每個數(shù)據(jù)科學(xué)家都應(yīng)該了解如何從pdf文件中提取數(shù)據(jù),并將數(shù)據(jù)轉(zhuǎn)換為諸如“csv”之類的格式,以便用于分析或構(gòu)建模型。
在本文中,我們將重點討論如何從pdf文件中提取數(shù)據(jù)表。類似的分析可以用于從pdf文件中提取其他類型的數(shù)據(jù),如文本或圖像。我們將說明如何從pdf文件中提取數(shù)據(jù)表,然后將其轉(zhuǎn)換為適合于進(jìn)一步分析和構(gòu)建模型的格式。我們將給出一個實例。

示例:使用Python從PDF文件中提取一個表格
a) 將表復(fù)制到Excel并保存為table_1_raw.csv

數(shù)據(jù)以一維格式存儲,必須進(jìn)行重塑、清理和轉(zhuǎn)換。
b) 導(dǎo)入必要的庫
- import pandas as pd
- import numpy as np
c) 導(dǎo)入原始數(shù)據(jù),重新定義數(shù)據(jù)
- df=pd.read_csv("table_1_raw.csv", header=None)
- df.values.shape
- df2=pd.DataFrame(df.values.reshape(25,10))
- column_names=df2[0:1].values[0]
- df3=df2[1:]
- df3.columns = df2[0:1].values[0]
- df3.head()
d) 使用字符串處理工具進(jìn)行數(shù)據(jù)糾纏
我們從上面的表格中注意到,x5、x6和x7列是用百分比表示的,所以我們需要去掉percent(%)符號:
- df4['x5']=list(map(lambda x: x[:-1], df4['x5'].values))
- df4['x6']=list(map(lambda x: x[:-1], df4['x6'].values))
- df4['x7']=list(map(lambda x: x[:-1], df4['x7'].values))
e) 將數(shù)據(jù)轉(zhuǎn)換為數(shù)字形式
我們注意到列x5、x6和x7的列值數(shù)據(jù)類型為string,因此我們需要將它們轉(zhuǎn)換為數(shù)值數(shù)據(jù),如下所示:
- df4['x5']=[float(x) for x in df4['x5'].values]
- df4['x6']=[float(x) for x in df4['x6'].values]
- df4['x7']=[float(x) for x in df4['x7'].values]
f) 查看轉(zhuǎn)換數(shù)據(jù)的最終形式
- df4.head(n=5)

g) 導(dǎo)出最終數(shù)據(jù)到一個csv文件
- df4.to_csv('table_1_final.csv',index=False)