Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-docx: Parse a table to Panda Dataframe

I'm using the python-docx library to extract ms word document. I'm able to get all the tables from the word document by using the same library. However, I'd like to parse the table into a panda data frame, is there any built-in functionality I can use to parse the table into data frame or I'll have to do it manually? Also, is there a possibility to know the heading name in which the table lies inside? Thank you

from docx import Document
from docx.shared import Inches
document = Document('test.docx')

tabs = document.tables
like image 638
Ali Asad Avatar asked Oct 06 '19 05:10

Ali Asad


2 Answers

A similar alternative (but I did not test using multiple tables).
This gave me the dataframe format I was looking for:

for table in firstdoc.tables:
    doctbls=[]
    tbllist=[]
    rowlist=[]
    for i, row in enumerate(table.rows):
        for j, cell in enumerate(row.cells):
            rowlist.append(cell.text)
        tbllist.append(rowlist)
        rowlist=[]
    doctbls=doctbls+tbllist

finaltables=pd.DataFrame(doctbls)     
display(finaltables)
like image 42
AshleyOboe Avatar answered Oct 20 '22 10:10

AshleyOboe


You can extract tables from the document in data-frame by using this code :

from docx import Document
import pandas as pd
document = Document('test.docx')

tables = []
for table in document.tables:
    df = [['' for i in range(len(table.columns))] for j in range(len(table.rows))]
    for i, row in enumerate(table.rows):
        for j, cell in enumerate(row.cells):
            if cell.text:
                df[i][j] = cell.text
    tables.append(pd.DataFrame(df))
print(tables)

You can get all the tables from the tables variable.

like image 144
abdulsaboor Avatar answered Oct 20 '22 09:10

abdulsaboor