2017-07-17 11 views
-4

我想將PDF轉換爲包含表格格式的數據框。我正在使用Python 3.6。使用Python將PDF轉換爲數據框

請幫我轉換一樣。

請按照鏈接PDF文件:

http://centerforcollegeaffordability.org/uploads/component-rankings-2014-v2.pdf

+0

Stackoverflow不是一個免費的代碼寫入服務。 –

+0

是的,先生,我知道。我在這裏學習。我是python的新手。我試圖解決相同的問題。我嘗試使用PyPDF2,但它沒有。請求您請建議任何解決方法。 –

+0

顯示你的嘗試。 –

回答

1

我已經找到了一條出路。我使用Tabula-py綁定和PyPDF2。

我正在使用PyPDF2獲取PDF頁面數量並使用它遍歷.pdf文件的每個頁面。

而且,Tabula用於提取數據並將其轉換爲數據幀。

如果還有更好的方法,請糾正。

import pandas as pd 
import numpy as np 
from tabula import read_pdf_table 
import PyPDF2 

reader = PyPDF2.PdfFileReader(open('Your Path', mode='rb')) 
m = reader.getNumPages() 
#print(reader) 
print(m) 
for i in range(m): 
    n = i+1 

    if n==1: 
     df = read_pdf_table('Your Path', pandas_options={'header': None, 'error_bad_lines': False}, pages=n) 
     index = np.where(df[0].isnull())[0] 
     sect = df.iloc[index[0]:index[-1]] 
     s = [] 
     headers = [] 
     for col in sect: 
      colnames = sect[col].dropna().values.flatten() 
      (s.insert(len(s), colnames)) 
      pic = [' '.join(s[col])] 
      for i in pic: 
       headers.append(i) 
     print(df) 
     df.drop(sect, inplace=True) 
     df.columns = headers 
     new_df = pd.DataFrame(columns=headers) 
     new_df = pd.concat([new_df, df], axis=0, ignore_index=True) 

    else: 
     df_2 = read_pdf_table('Your Path', pandas_options={'header': None, 'error_bad_lines': False, 'encoding': "ISO-8859-1"}, pages=n) 
     df_2.drop(sect, inplace=True) 
     df_2.columns = headers 
     new_df = pd.concat([new_df, df_2], axis=0, ignore_index=True) 

new_df.columns = headers 
print(new_df) 
new_df.to_csv('Your Path', index=False)