有条件地格式化Python pandas cell

时间:2016-12-17 23:15:10

标签: python pandas dataframe highlight conditional-formatting

我正在尝试根据单元格的值来着色,突出显示或改变对Python pandas DataFrame的喜爱。例如如果每行上的单元格大于该行第一列中的单元格,则将单元格突出显示为红色(或任何其他颜色),否则保持原样。

我在这里写了一个for循环:

<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@latest/dist/react.js"></script>
    <script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    <style>
        a.star:hover {
            cursor: pointer;
            color: red;
        }
        a.star {
            font-size: 2em;
        }
    </style>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

到目前为止,我还没有办法做到这一点。任何帮助都会很棒。

2 个答案:

答案 0 :(得分:8)

来自the style docs:

  

您可以应用条件格式,即视觉样式   DataFrame取决于其中的数据,使用DataFrame.style   属性。

import pandas as pd
df = pd.DataFrame([[2,3,1], [3,2,2], [2,4,4]], columns=list("ABC"))

df.style.apply(lambda x: ["background: red" if v > x.iloc[0] else "" for v in x], axis = 1)

enter image description here

编辑:要格式化特定单元格,您可以添加条件检查器以使用Series.iteritems()检查元素的名称,或使用enumerate()检查索引,例如如果要从第3列开始格式化,可以使用枚举并检查索引:

df = pd.DataFrame([[2,3,-3], [3,2,7], [2,4,4]], columns=list("ABC"))

df.style.apply(lambda x: ["background-color: #ff33aa" 
                          if (i >= 2 and (v > x.iloc[0] + x.iloc[1] 
                                          or v < x.iloc[0] - x.iloc[1])) 
                          else "" for i, v in enumerate(x)], axis = 1)

enter image description here

答案 1 :(得分:0)

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(4,3))
df.style.applymap(lambda x: 'background-color : yellow' if x>df.iloc[0,0] else '')

df