熊猫样式标签给出“ValueError:非唯一索引不支持样式”

Met*_*oll 5 python-3.x pandas

我想给我的数据框中的负数一个红色。但是当尝试使用以下代码实现时

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

s = df05.style.applymap(color_negative_red)

print(s)
Run Code Online (Sandbox Code Playgroud)

我收到以下值错误“ValueError:非唯一索引不支持样式。”

我必须在哪里寻找正确的输出?

jez*_*ael 9

我相信你需要独特的默认索引值DataFrame.reset_indexdrop=True

s = df05.reset_index(drop=True).style.applymap(color_negative_red)
Run Code Online (Sandbox Code Playgroud)

  • @jezrael 你知道为什么存在这种样式要求吗?要求听起来与我无关。谢谢 (2认同)