如何将数据框与突出显示列一起分离

How to segregate dataframe along with highlight column

import pandas as pd
test_df =pd.DataFrame({"col1":[1,12,3,4],
            "col2":[3,14,5,6],
             "col3":[4,5,6,7]})

print(test_df)
   col1  col2  col3
0     1     3     4
1    12    14     5
2     3     5     6
3     4     6     7

def highlight(row):
    ret =["" for _ in row.index]   
    if row['col3'] == 5:                                                                         
        ret[row.index.get_loc('col3')] ="background-color: #f2f20a"
    if row['col2'] == 5:                                                                         
        ret[row.index.get_loc('col2')] ="background-color: #f2f20a"
        
    return ret
dd= test_df.style.apply(highlight, axis=1)
print(dd)
    col1 col2   col3
0   1    3      4
1   12  14      **5**
2   3   **5**   6
3   4   6       7

我如何分离创建数据框或只有一个高亮行的 excel?在这种情况下,只有第 1、2 行会出现在单独的 excel 或数据帧中。

提前致谢!

使用:

m = (pd.concat([(test_df['col2'] == 5), 
                   (test_df['col3'] == 5)], axis=1)
          .reindex(test_df.columns, fill_value=False, axis=1))
print (m)
    col1   col2   col3
0  False  False  False
1  False  False   True
2  False   True  False
3  False  False  False

def highlight(x):
    c = "background-color: #f2f20a"

    # DataFrame of styles
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    # set columns by condition
    df1 = df1.mask(m, c)
    return df1


df1 = test_df[m.any(axis=1)]
print (df1)
   col1  col2  col3
1    12    14     5
2     3     5     6

原解:

def highlight(x):

    # DataFrame of styles
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    # set columns by condition
    df1.loc[x['col2'] == 5, 'col2'] = "background-color: #f2f20a"
    df1.loc[x['col3'] == 5, 'col3'] = "background-color: #f2f20a"

    return df1


test_df.style(highlight, axis=None)