【发布时间】:2021-03-04 18:08:32
【问题描述】:
我通过使用 pandas 和 Python .docx 模块的数据框中的数据在 Word 文档中添加表格。我希望数据值以我应用于数据框的格式样式出现在 Word 文档表中。某些列具有带逗号分隔符 {:,} 的数字格式,而某些列具有百分比格式 {:.2%}。
但是,在我将格式样式添加到数据框后,数据框变成了 Style 对象。然后,我无法将 Style 对象中的值添加到 Word 中的表中。
如何将格式样式应用于数据框中的值,以便它们在 Word 文档表中显示为样式?
import pandas as pd
import docx
import openpyxl
# initialize list of lists
data = [[150000, 100000,.14565], [250000, 200000,.16334]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Revenues', 'Expenditures', 'Surplus'])
# Apply style to pandas DataFrame
df = df.style.format({"Revenues": "${:20,.0f}","Expenditures": "${:20,.0f}","Surplus": "{:.2%}"})
# Create the Word Document
doc = docx.Document('hello.docx')
# add a table to the end and create a reference variable
# extra row is so we can add the header row
t = doc.add_table(df.shape[0]+1, df.shape[1])
# add the header rows.
for j in range(df.shape[-1]):
t.cell(0,j).text = df.columns[j]
# add the rest of the data frame
for i in range(df.shape[0]):
for j in range(df.shape[-1]):
t.cell(i+1,j).text = str(df.values[i,j])
doc.save('hello_python_output.docx')
【问题讨论】:
标签: pandas dataframe number-formatting python-docx