如何使用熊猫从Word文档(.docx)文件中的表创建数据框

如何使用熊猫从Word文档(.docx)文件中的表创建数据框,第1张

如何使用熊猫从Word文档(.docx)文件中的表创建数据

docx
总是从Word表中以文本(字符串)形式读取数据。

如果我们要解析具有正确dtypes的数据,则可以执行以下 *** 作之一:

  • 手动
    dtype
    为所有列指定(不灵活)
  • 编写我们自己的代码来猜测正确的dtypes(太难了,熊猫IO方法做得很好)
  • 将数据转换为CSV格式,然后
    pd.read_csv()
    猜测/推断正确的dtypes(我选择这种方式)

非常感谢@Anton vBR改进了功能!


import pandas as pdimport ioimport csvfrom docx import documentdef read_docx_tables(filename, tab_id=None, **kwargs):    """    parse table(s) from a Word document (.docx) into Pandas Dataframe(s)    Parameters:        filename:   file name of a Word document        tab_id:     parse a single table with the index: [tab_id] (counting from 0).         When [None] - return a list of Dataframes (parse all tables)        kwargs:     arguments to pass to `pd.read_csv()` function    Return: a single Dataframe if tab_id != None or a list of Dataframes otherwise    """    def read_docx_tab(tab, **kwargs):        vf = io.StringIO()        writer = csv.writer(vf)        for row in tab.rows: writer.writerow(cell.text for cell in row.cells)        vf.seek(0)        return pd.read_csv(vf, **kwargs)    doc = document(filename)    if tab_id is None:        return [read_docx_tab(tab, **kwargs) for tab in doc.tables]    else:        try: return read_docx_tab(doc.tables[tab_id], **kwargs)        except IndexError: print('Error: specified [tab_id]: {}  does not exist.'.format(tab_id)) raise

注意:您可能想添加更多检查和异常捕获…

例子:

In [209]: dfs = read_docx_tables(fn)In [210]: dfs[0]Out[210]:   A   B    C,X0  1  B1     C11  2  B2     C22  3  B3  val1, val2, val3In [211]: dfs[0].dtypesOut[211]:A       int64B      objectC,X    objectdtype: objectIn [212]: dfs[0].columnsOut[212]: Index(['A', 'B', 'C,X'], dtype='object')In [213]: dfs[1]Out[213]:   C1  C2          C3    Text column0  11  21         NaN  Test "quotes"1  12  23  2017-12-31 NaNIn [214]: dfs[1].dtypesOut[214]:C1   int64C2   int64C3  objectText column    objectdtype: objectIn [215]: dfs[1].columnsOut[215]: Index(['C1', 'C2', 'C3', 'Text column'], dtype='object')

解析日期:

In [216]: df = read_docx_tables(fn, tab_id=1, parse_dates=['C3'])In [217]: dfOut[217]:   C1  C2         C3    Text column0  11  21        NaT  Test "quotes"1  12  23 2017-12-31 NaNIn [218]: df.dtypesOut[218]:C1int64C2int64C3  datetime64[ns]Text column objectdtype: object


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5664112.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存