I have a CSV file I add the code to process data on it and know how to save the final dataframe to the same CSV by using to_csv
method. The problem is I want to add the background color to some of the columns, how can I do it?
Asked
Active
Viewed 7,744 times
2

piRSquared
- 285,575
- 57
- 475
- 624

kalpesh rawal
- 21
- 1
- 6
-
csv doesn't save color information about columns. You'd need to save the color information as another column or within the column name and have a custom csv reader to parse it out. I'm trying to say that csv doesn't do what you want it to and in order to make it do it anyway, it'll get ugly. – piRSquared Sep 05 '19 at 12:46
-
can you tell me how to add colour to the entire specific column including column_name and it's all Values of a dataframe ? means how can I get mentioned image like output in a Dataframe – kalpesh rawal Sep 05 '19 at 12:55
-
try using/googling `pd.ExcelWriter`, saving the results in .xlsx will allow you to color the column background. – BenSeedGangMu Sep 05 '19 at 13:30
1 Answers
6
I strongly suggest reading the guide in the docs
To see an example where column names are styled see this post by Scott Boston
style
with apply
df = pd.DataFrame([[0, 1], [2, 3]], ['A', 'B'], ['X', 'Y'])
def f(dat, c='red'):
return [f'background-color: {c}' for i in dat]
df.style.apply(f, axis=0, subset=['X'])
Multicolor
columns_with_color_dictionary = {'X': 'green', 'Y': 'cyan'}
style = df.style
for column, color in columns_with_color_dictionary.items():
style = style.apply(f, axis=0, subset=column, c=color)
style
Save color meta data in the column name
df.rename(columns=lambda x: f"{x}_{columns_with_color_dictionary.get(x)}") \
.to_csv('colorful_df.csv')
df_color = pd.read_csv('colorful_df.csv', index_col=0)
cmap = dict([c.split('_', 1) for c in df_color])
df_color.columns = df_color.columns.str.split('_', 1).str[0]
style = df_color.style
for column, color in cmap.items():
style = style.apply(f, axis=0, subset=column, c=color)
style
Save as HTML
from IPython.display import HTML
columns_with_color_dictionary = {'X': 'yellow', 'Y': 'orange'}
style = df.style
for column, color in columns_with_color_dictionary.items():
style = style.apply(f, axis=0, subset=column, c=color)
with open('df.html', 'w') as fh:
fh.write(style.render())
HTML(open('df.html').read())

piRSquared
- 285,575
- 57
- 475
- 624
-
i tried the above pieces of code but when i print, the pycharm give me a normal dataframe not colored df like you showed above the same thing in IDLE also – kalpesh rawal Sep 06 '19 at 02:56