使用熊猫对Excel工作表中的条件格式进行过滤

问题描述 投票:0回答:1

我有一个excel文件,其中某一列中的某些行的条件格式为红色。所以我的文件看起来像这样

enter image description here

现在,我必须在“学院”(College)列上应用该过滤器,以删除背景为红色的所有行。

enter image description here

并将其保存回文件。

我为此编写的代码是:

dataFrame_file = pd.read_excel(util.comcastFile2Path(), sheet_name='Sheet1')  //comcastFile2Path() gives path of file
def only_cells_with_red_background(cell):
    return cell if cell.style.bg_color in {utils.colors.red, 'FFFF0000'} else np.nan

df=dataFrame_file.style.applymap(only_cells_with_red_background,subset=['College'])
util.mergeFile(dataFrame_file,df,util.comcastFile2Path)

而且我的用于合并和保存文件的util类方法看起来像这样

def mergeFile(dataFrame_file, delete_frame, comcastFileName):
    dataFrame_file = dataFrame_file.merge(delete_frame, how='left', indicator=True).query(
        '_merge == "left_only"').drop('_merge', 1)
    saveFile(dataFrame_file,comcastFileName)

当我这样做时,我得到的错误是:

TypeError: Can only merge Series or DataFrame objects, a <class 'pandas.io.formats.style.Styler'> was passed

我该如何进一步?

提前感谢。

python excel dataframe conditional-formatting styleframe
1个回答
0
投票

[pd.read_excel不会从Excel文件中读取样式。

由于您使用[styleframe]标记了问题,所以我相信您想使用StyleFrame.read_excel(util.comcastFile2Path(), sheet_name='Sheet1', read_style=True)来读取文件。

然后您也不需要使用df.merge。您可以选择没有红色背景的行并保存新的StyleFrame对象:

from StyleFrame import StyleFrame, utils

def no_red_background_cell(cell):
    return cell if cell.style.bg_color not in {utils.colors.red, 'FFFF0000'} else np.nan

sf = StyleFrame.read_excel(util.comcastFile2Path(), sheet_name='Sheet1', read_style=True)
sf = StyleFrame(sf.applymap(no_red_background_cell).dropna(axis=(0, 1), how='all'))
sf.to_excel('output.xlsx').save()
© www.soinside.com 2019 - 2024. All rights reserved.