gpt4 book ai didi

python - 基于多种条件的 Pandas 风格?

转载 作者:行者123 更新时间:2023-12-02 19:41:39 25 4
gpt4 key购买 nike

我想根据 2-3 个条件为某些行着色:

df

    status days_since_claim claim_action
0 Closed 349 days No action
1 Closed 353 days No action
2 Granted 373 days Check account
3 Granted 431 days Account checked
4 Closed 448 days No action

我想根据所有三列填充背景

`backgroud_color: 'green' if 'status' == 'Closed' and claim_action == 'No action'

`backgroud_color: 'red' if 'status' == 'Granted' and claim_action == 'Check account' and 'days_since_claim' > 300`

I tried:

styled = mdf.style.applymap(lambda v: 'background-color: %s' %
'red' if v > 300 else "")
def color_s(df):
for i, row in df.iterrows():
if row['status'] == 'Closed':
.
.

我认为我无法理解样式如何工作的概念。有人可以用例子解释一下吗?

提前致谢。

最佳答案

您可以使用Styler.apply创建样式的DataFrame并使用 loc 按条件设置行:

def color(x):
c1 = 'background-color: green'
c2 = 'background-color: red'
c = ''
#compare columns
mask1 = (x['status'] == 'Closed') &
(x['claim_action'] == 'No action')
mask2 = (x['status'] == 'Granted') &
(x['claim_action'] == 'Check account') &
(x['days_since_claim'].dt.days > 300)
#DataFrame with same index and columns names as original filled empty strings
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
#modify values of df1 column by boolean mask
df1.loc[mask1, :] = c1
df1.loc[mask2, :] = c2
return df1

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

关于python - 基于多种条件的 Pandas 风格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60004318/

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