【问题标题】:How to segregate dataframe along with highlight column如何将数据框与突出显示列分开
【发布时间】:2022-02-21 18:04:04
【问题描述】:
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 或数据框中。

提前致谢!

【问题讨论】:

  • 您要选择第 1,2 行来创建一个新的 DataFrame 吗?这里有什么问题?

标签: python pandas dataframe exploratory-data-analysis styler


【解决方案1】:

用途:

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)

【讨论】:

  • @kundankaushik - 看起来更复杂。可能的解决方案是更改逻辑 - 首先在变量 m 中创建掩码,它用于突出显示值,然后用于过滤到 df1
  • @kundankaushik - 添加到答案。所以没必要创建df1
  • @kundankaushik - 所以需要先突出显示然后过滤?我认为不可能。
  • @kundankaushik - 我找到了解决方案 this - 但需要 StyleFrame,而不是 pandas DataFrame。如果需要,应该是这样。
  • @kundankaushik - 我认为只需要关于StyleFrame 的新问题。在 pandas 中,无法使用 StyleFrame 这样的样式。
猜你喜欢
  • 1970-01-01
  • 2021-08-04
  • 2015-12-21
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 2020-05-18
  • 2021-01-09
  • 2015-03-30
相关资源
最近更新 更多