gpt4 book ai didi

python - 如何根据值为 Python Pandas 中的整行着色?

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:10 25 4
gpt4 key购买 nike

所以我想出了如何使用 pandas 中的 Style 模块为单个单元格和列着色。但是,我想根据该行中单个单元格中的值为整行着色。

例如,如果 A 列中的单元格 C 的值为 23,则将 C 的行涂成黄色。

我该怎么做?

最佳答案

使用:

df =  pd.DataFrame({'A':[23,25,10], 'B':[7,8,3], 'C':[8,3,1]})
print (df)
A B C
0 23 7 8
1 25 8 3
2 10 3 1

def highlight_col(x):
#copy df to new - original data are not changed
df = x.copy()
#set by condition
mask = df['A'] == 23
df.loc[mask, :] = 'background-color: yellow'
df.loc[~mask,:] = 'background-color: ""'
return df

df.style.apply(highlight_col, axis=None)

picture

关于python - 如何根据值为 Python Pandas 中的整行着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47469478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com