我想进行条件格式设置,将其应用于 pandas 数据框中的另一列。所以我想将“timestart”和“timeend”列中的字体颜色更改为蓝色,如果“mark_start”、“mark_end”列中的值大于0。我使用了下面的代码,但我需要为另一列着色:
import pandas as pd
import numpy as np
lst = [['Load from table main', '2023-08-02 01:33:47' , 1, '2023-08-02 02:33:47' , 0],
['Load from table output', '2023-08-01 02:34:57' , 0, '2023-08-02 02:33:47' , 1]]
df = pd.DataFrame(lst,columns=['comment','timestart','mark_start','timeend','mark_end'])
col_background_name = ['mark_start','mark_end']
col_val = ['timestart','timeend']
def highlight_col_val(col):
if col.name in col_background_name:
return ['background-color:blue' if val == 1 else '' for val in col]
else:
return ['' for _ in col]
st = df.style.apply(highlight_col_val, axis=0)
st.to_excel("out.xlsx",engine='openpyxl')
“mark_start”列的值引用“timestart”列,“mark_end”列的值引用“timeend”列。
我尝试通过执行以下操作来做到这一点,但它不起作用
def highlight_col_val_three(col,col_val):
if col.name in col_background_name:
return ['background-color:blue' if val == 1 and col == col_val else '' for val in col]
else:
return ['' for _ in col]
st = df.style.apply(highlight_col_val_three, axis=0)
我需要将两个带有值的参数['mark_start','timestart']传递给函数defhighlight_col_val_ Three。 不知道怎么办
我已经探索了 style.apply 方法,但似乎找不到有效的方法。任何帮助将不胜感激。谢谢!
我尝试通过执行以下操作来做到这一点,但它不起作用
def highlight_col_val_three(col,col_val):
if col.name in col_background_name:
return ['background-color:blue' if val == 1 and col == col_val else '' for val in col]
else:
return ['' for _ in col]
st = df.style.apply(highlight_col_val_three, axis=0)