Pandas造型单细胞

2024-03-29 07:39:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建下面的数据帧,并试图更改我的“代码”单元格的背景,从我的最后一行开始,当它的长度不同于8时,但我不知道我哪里错了

def add_warn_color():
    return 'background-color: yellow'

    
def validate_data(row):        
    if len(row['code']) != 8:
        row['code'].style.applymap(add_warn_color)


data = {0: ['title1','ABC123ZX'], 1: ['title2', '9876QWERTYUI']}
df = pd.DataFrame().from_dict(data,orient='index',columns=['title','code'])
row = df.iloc[-1:,:]
validate_data(row)

我很确定我误解了什么,但我不明白


1条回答
网友
1楼 · 发布于 2024-03-29 07:39:41

只有DataFrame(不是Series)具有.style属性。我们需要使用列式样式,并将该样式应用于相关单元格。请注意,样式仅应用于返回的样式器


def warning_colors(s):
    # Mask: Is it the last row. Is the length != 8?
    warn = (s.reset_index().index == len(s) - 1) & (s.str.len() != 8)
    return ['background-color: yellow' if v else '' for v in warn]

data = {0: ['title1','ABC123ZX'], 1: ['title2', '9876QWERTYUI']}
df = pd.DataFrame.from_dict(data, orient='index', columns=['title','code'])

# Style only the 'code' column
dfs = df.style.apply(warning_colors, subset='code')
dfs

^{tb1}$

相关问题 更多 >