2

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?

Example data with colored columns

3
  • 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. Commented Sep 5, 2019 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 Commented Sep 5, 2019 at 12:55
  • try using/googling pd.ExcelWriter, saving the results in .xlsx will allow you to color the column background. Commented Sep 5, 2019 at 13:30

1 Answer 1

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'])

enter image description here


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

enter image description here


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

enter image description here


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())

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.