基于Python Pandas中列的值,突出显示DataFrame中的行

3
我一直在尝试根据多个条件在pandas数据帧中突出显示某些行。
我期望当目标列中的字符串符合函数中定义的条件时,整行都会被突出显示。
我尝试了不同组合的.style.apply方法,但它一直给我以下错误:
ValueError: style is not supported for non-unique indicies.
这是代码:
def highlight_rows(s):        
    if s['my_column'] == 'some_text':
        return 'background-color: green'
    elif s['my_column'] == 'somedifferent_text':
        return 'background-color: blue'

df.style.apply(highlight_rows, axis = 0)

我正在使用Python 3.6.5和Pandas 0.22.0。

你有什么想法,我做错了什么吗?

我应该传递不同的参数或者使用不同的循环吗?

谢谢。


错误看起来很明显...您的数据框具有非唯一索引(即,索引具有重复的值),而.style不支持该情况。您可以尝试使用df.reset_index().style.apply(highlight_rows, axis = 0) - undefined
谢谢@jdehesa,那个解决了错误。我以为是其他问题,因为我先尝试使用命令df.set_index(['my_column'], append = True)。现在没有报错了,但是在使用ExcelWriter方法导出数据框后,我没有看到任何行被突出显示。 - undefined
reset_index()方法会返回一个新的数据框,你可以使用df2 = df.reset_index(); df2.style.apply(highlight_rows, axis = 0)来创建df2并应用highlight_rows样式,然后导出df2 - undefined
1
信息:具有相同名称的两个列会生成相同的错误消息。 - undefined
2个回答

2
< p > apply 方法根据 axis=0axis=1 提取每列或每行。然后,您可以为行或列中的每个单元格添加任何样式。如果您想通过方法传递样式,则需要为数组的每个元素分配方法表达式。否则,它必须是 None 值。

def highlight_rows(s):
    con = s.copy()
    con[:] = None
    if (s['my_column'] == 'some_text'):
        con[:] = "background-color: green"
    elif (s['my_column'] == 'somedifferent_text'):
        con[:] = "background-color: blue"
    return con
        
df.style.apply(highlight_rows, axis=1)

0
假设s等于您的数据框: 尝试这个:
def file():
    styled = df.style.apply(highlight_rows, axis = 0)
    f = open('new_file.html', 'w')
    html = (styled.render())
    f.write(html)
    f.close()

def highlight_rows(s):        
    if s.my_column == 'some_text':
        return ['background-color: green'] * s.size
    elif s.my_column == 'somedifferent_text':
        return ['background-color: blue'] * s.size

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接