【问题标题】:xlsxwriter pandas frame: to highlight rows if there are blank cells within a columnxlsxwriter pandas frame:如果列中有空白单元格,则突出显示行
【发布时间】:2019-12-02 06:01:23
【问题描述】:

我有一个带有 T 列的熊猫框架,其中有一些空白单元格。我想突出显示任何包含空白单元格的行

我一直在尝试使用 .format,但它只突出显示空白单元格而不是整行。

worksheet.conditional_format('A1:T18', {'type':'no_blank'
                                       'format':green_fmt}

)

预期:整行以浅绿色突出显示 实际结果:只有空白单元格被突出显示

【问题讨论】:

  • 尝试将其写入 csv 文件
  • 有没有办法写入 xlsx 文件?

标签: python pandas syntax-highlighting xlsxwriter


【解决方案1】:

如果空白值是缺失值,请使用带有自定义函数的 pandas styles

df = pd.DataFrame({'T':[np.nan, np.nan, 1, 5],
                   'A':range(4),
                   'B':list('abcd')})
print (df)
     T  A  B
0  NaN  0  a
1  NaN  1  b
2  1.0  2  c
3  5.0  3  d

def highlight(x):
    c = 'background-color: lime'

    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    m = x.isna().any(axis=1)
    df1 = df1.mask(m, c)
    return df1

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

【讨论】:

  • 感谢您的回答,杰兹瑞尔。有没有办法使用 xlsxwriter 引擎来做到这一点,因为我的大部分代码都是基于这个特定的引擎?
  • @DatNguyen - 不确定,我检查了docs,似乎不受支持。
  • 是的,我也在检查它,但发现它只突出显示单元格而不是整行
  • 其实我想我可以找到nan行的索引,然后用set format给它们上色
  • 然后使用循环和函数 worksheet.set_row() 并为其着色:)))
【解决方案2】:

这对我有用:

import pandas as pd
import numpy as np
import xlsxwriter

# Create a test dataframe (borrowed by jezrael)
df = pd.DataFrame({'T':[np.nan, np.nan, 1, 5],
                   'A':range(4),
                   'B':list('abcd')})

# Create a Pandas Excel writer using XlsxWriter as the engine
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object
df.to_excel(writer, sheet_name='Sheet1', index=False)

# Get the xlsxwriter workbook and worksheet objects
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Define the format for the row
cell_format = workbook.add_format({'bg_color': 'yellow'})

# Grab the index numbers of the rows where specified column has blank cells (in this case column T)
rows_with_blank_cells = df.index[pd.isnull(df['T'])]

# For loops to apply the format only to the rows which have blank cells
for col in range(0,df.shape[1]): # iterate through every column of the df
    for row in rows_with_blank_cells:
        if pd.isnull(df.iloc[row,col]): # if cell is blank you ll get error, that's why write None value
            worksheet.write(row+1, col, None, cell_format)
        else:
            worksheet.write(row+1, col, df.iloc[row,col], cell_format)

# Finally output the file
writer.save()

【讨论】:

    【解决方案3】:

    1. 构建一个函数,如果找到 NaN,则突出显示行。

    2. dataframe.style.apply(function_name, axis=1)

    # Function to color entire row
    def color(row):
        if row.isnull().values.any() == True:
            return ['background-color: red'] * len(row)
        return [''] * len(row)
    
    # Create a dataframe
    data = pd.DataFrame({"col1":col1, "col2":col2, "col3":col3})
    
    # Empty values
    col1[3], col2[0] = None, None
    
    # Apply the function
    data.style.apply(color, axis=1)
    

    【讨论】:

    • 感谢您回答我的问题,TheSHETTY。由于我是高亮显示并导出到xlsx文件,所以单独pandas是不支持这个操作的。因此,我使用 xlsxwriter 引擎来执行此操作。我刚刚想出尝试索引那些空白的行号,然后用它来设置颜色:)
    • 那么申请.to_excel('styled.xlsx', engine='openpyxl', index=False)会有帮助吗?
    • 我不确定 openpyxl 引擎,因为我没有机会经常使用它。但是对于 xlsxwriter 引擎来说,查找索引和使用 set_row 的方式真的很好用
    • 查看notebook。 openpyxl 引擎也给出了正确的结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多