I'm currently facing a challenge while attempting to apply color to a single column in a Pandas DataFrame. I have this code snippet that accomplishes the task, but it introduces some side effects that are proving challenging to resolve.
import pandas as pd
from termcolor import colored
# Sample DataFrame
data = {'A': [1.10, -2.22, 3.33, -4.40],
'B': [-5.50, 6.61, 7.70, -8.80]}
df = pd.DataFrame(data)
print(df)
# Function to apply color to a single value
def colorize_value(value):
return colored(value, 'blue') if value > 0 else colored(value, 'red')
# Specify the column you want to colorize
column_to_colorize = 'A'
# Apply color to the specified column using apply
df[column_to_colorize] = df[column_to_colorize].apply(colorize_value)
# Display the result
print(df)
While the above code achieves desired colorization effect, I've encountered the following issues:
- Column header misalignment: The column header appears misaligned after applying the colorization.
- Justification of column values: The colorization messes up the justification of the column values.
I managed to address the justification issue by modifying the colorize_value function to include formatting:
def colorize_value(value):
return colored("%.2f" % value, 'blue') if value > 0 else colored("%.2f" % value, 'red')
However, the problem of column misalignment persists, and I haven't found a satisfactory solution yet.
Any suggestions or insights on how to resolve the column misalignment issue would be greatly appreciated.

In the meantime, I've devised a workaround (though I'm uncertain if this is the optimal solution), which involves assigning color to the column header as well.