I want to set the background color of the whole table, then change the background color to red if the cell in the “DATA_PASS” column is false.
The following is my code by I can’t seem to get the applymap
to work.
import pandas as pd
# Define the data
data = {
'Column1': [10, 20, 30],
'Column2': [40, 50, 60],
'DATA_PASS': [True, False, True]
}
# Create DataFrame
df = pd.DataFrame(data)
# Function to highlight the cell in red if DATA_PASS is False
def highlight_data_pass(val):
return 'background-color: red' if val == False else ''
# Apply the styles and properties
styler = df.style
.applymap(highlight_data_pass, subset=['DATA_PASS'])
.set_table_styles([
{'selector': 'th', 'props': [
('background-color', '#606060'),
('color', 'white'),
('width', '100px'),
('height', '30px')
]},
{'selector': 'td', 'props': [
('background-color', '#A9A9A9'),
('color', 'black'),
('width', '250px'),
('height', '30px')
]}
])
.set_properties(**{
'border': '1px solid black'
})
# Display the styled DataFrame
styler
The red cell is visible if I do the following but I lose the colors of other cells that I want.
styler = df.style.applymap(highlight_data_pass, subset=['DATA_PASS'])
Reversing the order also did not work, the cell did not turn red.
styler = df.style.set_table_styles([
{'selector': 'th', 'props': [
('background-color', '#606060'),
('color', 'white'),
('width', '100px'),
('height', '30px')
]},
{'selector': 'td', 'props': [
('background-color', '#A9A9A9'),
('color', 'black'),
('width', '250px'),
('height', '30px')
]}
])
.set_properties(**{
'border': '1px solid black'
})
.applymap(highlight_data_pass, subset=['DATA_PASS'])
New contributor
glitchyfingers is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.