Python XLSX框架:如果列中有空白单元格,则高亮显示行

Python XLSX框架:如果列中有空白单元格,则高亮显示行,python,pandas,syntax-highlighting,xlsxwriter,Python,Pandas,Syntax Highlighting,Xlsxwriter,我有一个带T列的熊猫框架,它有一些空白单元格。我想突出显示所有包含空白单元格的行 我一直尝试使用.Frad,但它只突出空白单元格,而不是整行。 worksheet.conditional_format('A1:T18', {'type':'no_blank' 'format':green_fmt} ) 预期:整行以浅绿色突出显示 实际结果:只有空白单元被突出显示如果空白值缺失,则使用具有自定义功能的大熊猫: df

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

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

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

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

如果空白值缺失,则使用具有自定义功能的大熊猫:

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)

1。构建一个函数,在找到NaN时突出显示行

2.dataframe.style.apply(函数名,axis=1)

这对我很有用:

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()

试着将其写入csv文件有没有办法写入xlsx文件?谢谢你的回答,耶兹雷尔。有没有办法使用xlsxwriter引擎来实现这一点,因为我的大部分代码都基于这个特定的引擎?@DatNguyen-不确定,我检查了一下,似乎不受支持。是的,我也检查了一下,但发现它只突出显示了单元格,而不是整行,我想我可以找到nan行的索引,然后使用set格式为它们着色,然后使用循环和函数工作表。set_row()并将其着色:))谢谢您回答我的问题,Thehetty。因为我高亮显示它并将其导出到xlsx文件,所以熊猫本身不支持此操作。因此,我使用xlsxwriter引擎来实现这一点。我刚刚想出了一个办法,尝试为这些空白行的行号编制索引,然后用它来设置颜色:),所以将
应用到excel('styled.xlsx',engine='openpyxl',index=False)
会有帮助吗?我不确定openpyxl引擎,因为我没有机会经常使用它。但是对于xlsxwriter引擎,查找索引和使用set_行的方法非常有效。请检查这一点。openpyxl引擎也给出了正确的结果
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()