【问题标题】:pandas style tag give "ValueError: style is not supported for non-unique indices"熊猫样式标签给出“ValueError:非唯一索引不支持样式”
【发布时间】:2022-04-14 20:00:07
【问题描述】:

我想将我的数据框中的负数设为红色。 但是当试图用下面的代码实现时

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)

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

我必须从哪里获得正确的输出?

【问题讨论】:

  • 张贴这个以防有人需要这个:我最近遇到了这个问题。经过多次尝试,我意识到数据框中列的名称是问题所在,因为它们不是唯一的。重命名列的简单命令解决了这个问题,接下来是一些示例: df.columns = range(df.size) df.columns = ['A', 'B', 'C'] df.T.reset_index(drop =真).T

标签: python-3.x pandas


【解决方案1】:

我相信您需要 DataFrame.reset_indexdrop=True 的唯一默认索引值:

s = df05.reset_index(drop=True).style.applymap(color_negative_red)

【讨论】:

  • 如果你想设置一个新的CategoricalIndex,例如cm.set_index(pandas.CategoricalIndex(['TN', 'FN', 'FP', 'FN'])).style?这会产生相同的异常。
  • @DanielleMadeley - 不幸的是还不支持。
  • @jezrael 你知道为什么存在这种样式要求吗?要求听起来与我无关。谢谢
  • 我的数据框有唯一的索引,但仍然不起作用。即使尝试上述方法,重置索引也不起作用。
猜你喜欢
  • 2020-11-01
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 2012-08-12
  • 2019-09-08
  • 2020-08-03
  • 1970-01-01
相关资源
最近更新 更多