Are you tired of manually coloring cells in Excel? Pandas, a powerful data manipulation library in Python, offers an efficient way to add color to your data. By leveraging pandas' styling capabilities, you can enhance the visual appeal of your data and make it more understandable. Let's explore how to apply colors to your Excel data using pandas.

Why Use Colors in Excel with Pandas?

Adding color to your Excel data can significantly improve readability and highlight important information. It's particularly useful when dealing with large datasets or complex analyses. By applying colors, you can:
- Draw attention to specific data points or trends
- Differentiate between categories or groups
- Make your data easier to scan and understand

Getting Started with Pandas and Excel
Before you begin, ensure you have pandas and openpyxl installed. If not, you can install them using pip:

pip install pandas openpyxl
Reading Excel Files with Pandas
First, let's read an Excel file using pandas. We'll use the read_excel function from the pandas.io.excel module.

import pandas as pd
df = pd.read_excel('your_file.xlsx')
Applying Colors to Excel Data with Pandas

Pandas provides the style attribute to apply formatting to dataframes. To add color, you can use the applymap function with a custom color function. Here's how to do it:
Applying a Single Color




















Let's apply a light blue color to the entire dataframe.
def color_blue(val):
return 'background-color: lightblue'
df.style.applymap(color_blue)
Applying Colors Based on Conditions
You can also apply colors based on conditions. For example, let's highlight values greater than 100 in red:
def color_red(val):
return 'background-color: red' if val > 100 else ''
df.style.applymap(color_red)
Applying Colors to Specific Columns
To apply colors to specific columns, you can use the apply function with a custom color function. Here's how to highlight even-indexed rows in a column named 'A':
def color_even(val, color='lightgray'):
return 'background-color: %s' % color if val % 2 == 0 else ''
df.style.apply(color_even, subset=['A'])
Exporting the Styled Dataframe to Excel
After applying colors, you can export the styled dataframe back to an Excel file using the to_excel function with the engine='openpyxl' argument:
df.style.applymap(color_blue).to_excel('styled_file.xlsx', engine='openpyxl')
Conclusion
In this article, we've explored how to apply colors to your Excel data using pandas. By leveraging pandas' styling capabilities, you can enhance the visual appeal of your data and make it more understandable. Whether you're highlighting specific data points, differentiating between categories, or making your data easier to scan, adding color can significantly improve the readability of your Excel files.