pandas.to_csv(),带有一些粗体字

时间:2018-10-15 14:33:38

标签: python excel python-3.x pandas dataframe

我有数据框

df = [["A1" "B2" "C3"] ["D4" "E5" "F6"]]

(所有文本均为字符串) 我想使用df.to_csv()将其保存到文件中,并将文本“ E5”涂成彩色/粗体。 能做到吗?

1 个答案:

答案 0 :(得分:1)

逗号分隔值(csv)文件不包含任何格式信息,因此您需要使用Excel格式来完成所需的操作。您可以执行以下操作:

import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame([["A1", "B2", "C3"], ["D4", "E5", "F6"]])

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("test.xlsx", engine='xlsxwriter')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = workbook.add_worksheet('Sheet1')

# Add a header format.
header_format = workbook.add_format({'bold': True})

# Write the column headers with the defined format.
for i, row in enumerate(df.values):
    for j, val in enumerate(row):
        if val=='E5': worksheet.write(i, j, val, header_format)
        else: worksheet.write(i, j, val)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

这将输出:

enter image description here