python - 使用 pandas 过滤 excel 工作表中的条件格式

标签 python excel dataframe conditional-formatting styleframe

我有一个 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

我怎样才能走得更远?

提前致谢。

最佳答案

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

由于您使用 标记了问题我相信您打算使用 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()

关于python - 使用 pandas 过滤 excel 工作表中的条件格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59936682/

相关文章:

python - 如何获取包含列表或值的列 pandas 的唯一值?

excel - 将 Excel 中的长日期字符串转换为可排序的日期/时间格式

excel - 如何使用 VBA 在 Internet Explorer 中单击按钮

python - 创建前 n 个值的数据框的更有效方法 - python

python - Pandas 如何将所有字符串值转换为 float

python - 一次进行多个单独的 2d 旋转

python - 为什么 df.head() 在 python 中不起作用

重新索引和填充 R 数据帧

python - 在 pyspark 中将数据框保存到本地驱动器上的 JSON 文件

excel - CSV 中数据提取末尾的尾随逗号