我想设置整个表格的背景颜色,然后如果“DATA_PASS”列中的单元格为 false,则将背景颜色更改为红色。
以下是我的代码,我似乎无法让
applymap
工作。
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
如果我执行以下操作,红色单元格是可见的,但我丢失了我想要的其他单元格的颜色。
styler = df.style.applymap(highlight_data_pass, subset=['DATA_PASS'])
颠倒顺序也不起作用,单元格没有变红。
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']) \
你可以尝试这样的事情:
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; color: black; width: 250px; height: 30px"
if not val
else "background-color: #A9A9A9; color: black; width: 250px; height: 30px"
)
# Apply the styles and properties
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"})
.map(highlight_data_pass)
)
# Display the styled DataFrame
styler
输出: