如何将OpenDocument电子表格转换为pandas数据框架?

2024-06-10 07:39:17 发布

您现在位置:Python中文网/ 问答频道 /正文

Python库可以读取Excel电子表格,并使用pandas.read_excel(file)命令将其转换为pandas.DataFrame。在引擎盖下,它使用xlrd库,其中does not supportods文件。

对于ods文件是否有一个等价的pandas.read_excel?如果没有,如何对打开的文档格式的电子表格(ods文件)执行相同的操作?ODF被LibreOffice和OpenOffice使用。


Tags: 文件命令dataframepandasreadnotodsexcel
3条回答

下面是一个使用ezodf模块的快速而肮脏的黑客:

import pandas as pd
import ezodf

def read_ods(filename, sheet_no=0, header=0):
    tab = ezodf.opendoc(filename=filename).sheets[sheet_no]
    return pd.DataFrame({col[header].value:[x.value for x in col[header+1:]]
                         for col in tab.columns()})

测试:

In [92]: df = read_ods(filename='fn.ods')

In [93]: df
Out[93]:
     a    b    c
0  1.0  2.0  3.0
1  4.0  5.0  6.0
2  7.0  8.0  9.0

注意:

  • 所有其他有用的参数,如headerskiprowsindex_colparse_cols,都没有在这个函数中实现-如果您想实现它们,请随时更新这个问题
  • ezodf取决于lxml确保已安装

这在熊猫0.25中是本地可用的。只要你安装了odfpy你就可以

pd.read_excel("the_document.ods", engine="odf")

您可以使用以下模块在Python中读取ODF(Open Document Format.ods)文档:

使用ezodf,一个简单的ODS到DataFrame转换器可能如下所示:

import pandas as pd
import ezodf

doc = ezodf.opendoc('some_odf_spreadsheet.ods')

print("Spreadsheet contains %d sheet(s)." % len(doc.sheets))
for sheet in doc.sheets:
    print("-"*40)
    print("   Sheet name : '%s'" % sheet.name)
    print("Size of Sheet : (rows=%d, cols=%d)" % (sheet.nrows(), sheet.ncols()) )

# convert the first sheet to a pandas.DataFrame
sheet = doc.sheets[0]
df_dict = {}
for i, row in enumerate(sheet.rows()):
    # row is a list of cells
    # assume the header is on the first row
    if i == 0:
        # columns as lists in a dictionary
        df_dict = {cell.value:[] for cell in row}
        # create index for the column headers
        col_index = {j:cell.value for j, cell in enumerate(row)}
        continue
    for j, cell in enumerate(row):
        # use header instead of column index
        df_dict[col_index[j]].append(cell.value)
# and convert to a DataFrame
df = pd.DataFrame(df_dict)

p.S.

  • 已在问题跟踪程序pandas上请求ODF电子表格(.ods文件)支持,但仍未实现。

  • 在未完成的PR9070中使用ezodf在pandas中实现ODF支持。这个PR现在已经关闭了(阅读PR进行技术讨论),但是它仍然可以作为thispandasfork中的一个实验特性使用。

  • 还有一些暴力方法可以直接从XML代码中读取(here

相关问题 更多 >