当我调用 style.apply 时函数没有被调用

function not being called when I call style.apply

我想对整行应用一些样式,我正在这样做。

df = pd.DataFrame({
    'correlation':[0.5, 0.1,0.9],
    "volume": [38,45,10]})

def highlight_col(x):
    #copy df to new - original data are not changed
    df = x.copy()
    #set by condition
    mask = df['volume'] <= 40
    df.loc[mask, :] = 'background-color: yellow'
    df.loc[~mask,:] = 'background-color: ""'
    return df    

df.style.apply(highlight_col, axis=None)

但我发现没有任何反应。有人可以指导我正确的方向吗?

PS:我相信它应该调用“highlight_col”函数,但它不会。

看看 pandas 提供的 styling guide

此输出上的函数 df.style.apply() return a Styler object, so your dataframe don't contain the styiling but you need to save the output of the apply function and use to_excel()。你的代码我直接做了,没有保存

我对你的代码进行了一些测试,看看:

import pandas as pd

df = pd.DataFrame({
    'correlation':[0.5, 0.1,0.9],
    "volume": [38,45,10]})

def highlight_col(x):
    #copy df to new - original data are not changed
    df = x.copy()
    #set by condition
    mask = df['volume'] <= 40

    df.loc[mask, :] = "background-color: yellow"
    df.loc[~mask,:] = ''

    return df    

df.style.apply(highlight_col, axis=None).to_excel('test.xlsx')

这会产生以下输出:

将颜色设置为:df.loc[~mask,:] = "background-color: ''" 生成警告:CSSWarning: Unhandled color format: "''" 并将颜色设置为黑色,将行更改为 df.loc[~mask,:] = '' 即可解决。这将产生:

如果你真的想要黑行,最好指定为"background-color: black"

您还可以将 df.style.apply(highlight_col, axis=None).to_excel('test.xlsx') 行更改为:

s = df.style.apply(highlight_col, axis=None)
s.to_excel('test.xlsx')

它将产生相同的输出:


要将 Styler 设为 HTML 格式,您只需使用 render() 函数并打印输出:

s = df.style.apply(highlight_col, axis=None)
print(s.render())

您也可以使用 _repr_html_:

s = df.style.apply(highlight_col, axis=None)
print(s._repr_html_())

输出:

<style  type="text/css" >
    #T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow0_col0 {
            background-color:  yellow;
        }    #T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow0_col1 {
            background-color:  yellow;
        }    #T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow1_col0 {
            background-color:  black;
        }    #T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow1_col1 {
            background-color:  black;
        }    #T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow2_col0 {
            background-color:  yellow;
        }    #T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow2_col1 {
            background-color:  yellow;
        }</style><table id="T_c4d4737f_0729_11eb_9637_dcfb48aafb0f" ><thead>    <tr>        <th class="blank level0" ></th>        <th class="col_heading level0 col0" >correlation</th>        <th class="col_heading level0 col1" >volume</th>    </tr></thead><tbody>
                <tr>
                        <th id="T_c4d4737f_0729_11eb_9637_dcfb48aafb0flevel0_row0" class="row_heading level0 row0" >0</th>
                        <td id="T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow0_col0" class="data row0 col0" >0.5</td>
                        <td id="T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow0_col1" class="data row0 col1" >38</td>
            </tr>
            <tr>
                        <th id="T_c4d4737f_0729_11eb_9637_dcfb48aafb0flevel0_row1" class="row_heading level0 row1" >1</th>
                        <td id="T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow1_col0" class="data row1 col0" >0.1</td>
                        <td id="T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow1_col1" class="data row1 col1" >45</td>
            </tr>
            <tr>
                        <th id="T_c4d4737f_0729_11eb_9637_dcfb48aafb0flevel0_row2" class="row_heading level0 row2" >2</th>
                        <td id="T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow2_col0" class="data row2 col0" >0.9</td>
                        <td id="T_c4d4737f_0729_11eb_9637_dcfb48aafb0frow2_col1" class="data row2 col1" >10</td>
            </tr>
    </tbody></table>

如果您只想更改单元格的样式而不是行的样式,请查看以下可能的解决方案:

import pandas as pd

df = pd.DataFrame({
    'correlation':[0.5, 0.1,0.9],
    "volume": [38,45,10]})

def highlight_col(x):
    if(x.name == 'volume'):
        mask = x <= 40
        return ['background-color: yellow' if v else '' for v in mask]
    return [''] * len(x)

df.style.apply(highlight_col).to_excel('test.xlsx')

输出: