Vin*_*e M 5 python dataframe pandas pandas-styles
我想根据另一列的值对一列上的 DataFrame 的红色单元格进行着色。
这是一个例子:
df = pd.DataFrame([
{ 'color_A_in_red': True , 'A': 1 },
{ 'color_A_in_red': False , 'A': 2 },
{ 'color_A_in_red': True , 'A': 2 },
])
Run Code Online (Sandbox Code Playgroud)
我知道如何将 df 的单元格着色为红色,但仅基于该单元格的值,而不是另一个单元格的值:
df_style = df.style
df_style.applymap(func=lambda x: 'background-color: red' if x == 2 else None, subset=['A'])
df_style
Run Code Online (Sandbox Code Playgroud)
有没有办法根据另一列的值对 DataFrame 的单元格进行着色?
对样式的 DataFrame 使用自定义函数是最灵活的解决方案:
def highlight(x):
c = f"background-color:red"
#condition
m = x["color_A_in_red"]
# DataFrame of styles
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
# set columns by condition
df1.loc[m, 'A'] = c
return df1
df.style.apply(highlight, axis=None)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4258 次 |
| 最近记录: |