【问题标题】:Highlighting rows using index numbers in pandas dataframe在熊猫数据框中使用索引号突出显示行
【发布时间】:2020-05-25 19:16:01
【问题描述】:

我正在尝试根据索引值突出显示完整的行。这是我所做的:

df = pd.read_excel(module)
rows = df.index[df['MYCOLUMN'].str.contains(command, na=False)].tolist()

if rows: 
        df.style.apply(lambda x: ['background: red' if x.name in rows else '' for i in x], axis=1)
        df.to_excel(module, index = False) 

但是该行没有得到高亮显示,我的 Excel 格式也发生了变化。有人能说出正确的做法吗?

【问题讨论】:

  • 使用openpyxl ..这样的作品要好得多

标签: python excel python-3.x pandas indexing


【解决方案1】:

您可以使用Styler.apply 创建样式的DataFrame,并使用loc 通过掩码设置行:

def color(x): 
   c1 = 'background-color: red'
   c = ''
   m1 = df['MYCOLUMN'].str.contains(command, na=False)

   df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
   df1.loc[m1, :] = c1
   return df1

(df.style.apply(color,axis=None)
         .to_excel('styled.xlsx', engine='openpyxl', index=False))

对我来说,函数外的工作变量如下:

def color(x): 
   c = ''
   m1 = df['MYCOLUMN'].str.contains(command, na=False)

   df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
   df1.loc[m1, :] = c1
   return df1

command = 'test'
c1 = 'background-color: red'

(df.style.apply(color, axis=None)
         .to_excel('styled.xlsx', engine='openpyxl', index=False))

【讨论】:

  • 如何在函数'color'中传递变量??
猜你喜欢
  • 2018-10-10
  • 2020-11-01
  • 2022-08-19
  • 2014-10-11
  • 2021-02-26
  • 1970-01-01
  • 2022-07-10
  • 1970-01-01
  • 2022-08-19
相关资源
最近更新 更多