Reputation: 1960
I have the dataframe
df = [["A1" "B2" "C3"] ["D4" "E5" "F6"]]
(All text are strings)
And I want to save it to a file using df.to_csv()
with the text "E5" coloured / bold.
Can it be done?
Upvotes: 3
Views: 5748
Reputation: 9019
Comma-separated values (csv) files do not contain any formatting information, therefore you need to use an Excel format to accomplish what you want. You can do something like the following:
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()
This will output:
Upvotes: 6