【问题标题】:How to style a Python Pandas Dataframe using dictionary如何使用字典设置 Python Pandas 数据框的样式
【发布时间】:2020-11-20 20:43:51
【问题描述】:

我有以下索引为“NUM”的熊猫数据框:

我想使用以下字典为单元格添加颜色:

d =  {'R1': [1,2,3,4,5,6,7,8,9,10]
  ,'R2': [3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
  ,'R3': [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
  ,'R4': [11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]
  ,'R5': [17,18,19,20,21,22,23,24,25,26,27,28]
}

字典值(列表)中的值是数据框中的索引。 我想为单元格添加背景颜色,例如在“R1”列颜色 1 到 10 中,在“R2”列颜色 3 到 20 中等等。

谢谢

【问题讨论】:

    标签: python pandas dataframe dictionary styles


    【解决方案1】:

    你可以试试:

    df.style.apply(
        lambda x: ['background-color:red' if i in d[x.name] else '' 
                   for i in np.arange(len(x))+1]
    )
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-01
      • 2023-01-20
      • 2013-09-12
      • 2016-04-07
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多