Я понимаю, что это уже было рассмотрено здесь (например, Запись Python Pandas DataFrame в документ Word , python -docx: Разобрать таблицу в Panda Dataframe ). Тем не менее, я надеюсь, что этот вопрос был другим.
Я использовал value_counts()
и сгенерировал DataFrame, как показано ниже:
df = sns.load_dataset('tips')
object_cols = list(df.select_dtypes(exclude=['int', 'float', 'int64', 'float64', 'int32', 'float32']).columns)
# Value Count & Percentage for object columns
c = df[object_cols].apply(lambda x: x.value_counts()).T.stack().astype(int)
p = (df[object_cols].apply(lambda x: x.value_counts(normalize=True)).T.stack() * 100).round(2)
cp = pd.concat([c,p], axis=1, keys=['Count', 'Percentage %'])
cp
DataFrame выглядит так:
Count Percentage %
sex Female 87 35.66
Male 157 64.34
smoker No 151 61.89
Yes 93 38.11
day Fri 19 7.79
Sat 87 35.66
Sun 76 31.15
Thur 62 25.41
time Dinner 176 72.13
Lunch 68 27.87
Я пытаюсь добавить указанный выше DataFrame в виде таблицы в документ, используя python-docx
import docx
from docx import Document
doc = Document()
doc.add_paragraph("Value Counts: ")
t = doc.add_table(cp.shape[0]+1, cp.shape[1])
# Set table style
t.style = 'Colorful List Accent 1'
# add the header rows.
for j in range(cp.shape[-1]):
t.cell(0,j).text = cp.columns[j]
# add the rest of the data frame
for i in range(cp.shape[0]):
for j in range(cp.shape[-1]):
t.cell(i+1,j).text = str(cp.values[i,j])
filename = "output/ValueCOunts_Report.docx"
# save the docx
doc.save(filename)
Я могу добавить таблицу как
Count Percentage %
87 35.66
157 64.34
151 61.89
.....
.....
.....
введите описание изображения здесь
Как добавить в документ полный DataFrame с индексами в виде таблицы?