python - Pandas 使用函数突出显示具有条件的 excel 列

标签 python pandas

我有一个正在写入 excel 的 Pandas 数据框 (Pre_Final_DataFrame)。

如果相应行在任何以“Result_”开头的列上有“不匹配”字样,我需要在 Excel 中突出显示该行。

因此,我决定使用一个数组来了解需要突出显示的数组。

但现在,我更喜欢使用函数来突出显示的方法,因为它太慢了。 请帮我解决这个问题。

简而言之,我正在使用 Pandas 编写一个 excel 数据框,它有数百万条记录,我希望仅当具有以“Result_”开头的名称

Excel 中显示的预期结果如下所示,

输入代码以数据框开头:-

import pandas as pd

data = {
     'ColA':[1, 1], 
     'ColB':[1, 1],
     'Result_1':['Match', 'Match'], 
     'ColA1':[1, 2], 
     'ColB1':[1, 1],
     'Result_2':['No Match', 'Match'],  
     }

Pre_Final_DataFrame = pd.DataFrame(data)

ResultColumns_df = Pre_Final_DataFrame.filter(like='Result_')
ResultColumns_df_false =ResultColumns_df[ResultColumns_df.values  == "No Match"]
RequiredRows_Highlight = ResultColumns_df_false.index.tolist()

writer = pd.ExcelWriter(OutputName,date_format='%YYYY-%mm-%dd',datetime_format='%YYYY-%mm-%dd')
Pre_Final_DataFrame.to_excel(writer,'Sheet1',index = False)
writer.save()

预期输出:

enter image description here

最佳答案

我们可以使用 StyleFrame 包将其读入 excel 表格。

import pandas as pd
from StyleFrame import StyleFrame, Styler

df = pd.read_excel("Your Excel Sheet")
sf = StyleFrame(df)

style = Styler(bg_color='yellow') 
for col in df:
     sf.apply_style_by_indexes(sf[sf[col]== 'No Match'],styler_obj=style)

sf.to_excel('test.xlsx').save()

这帮助我获得了一个输出 Excel 表,其中突出显示了所有行,其中至少包含一列值为 No Match

希望这对您有所帮助。干杯

关于python - Pandas 使用函数突出显示具有条件的 excel 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54255345/

相关文章:

python - 如何计算 Pandas 中的分类时间序列数据

python - Pandas read_csv 的 ParserError

python - 按 dtype 和列名选择 Pandas 列

python - 在python中解压没有临时文件的bz2 url

python - Pandas DataFrame.apply 对于 scipy.stats 来说非常慢

python - 从 Pandas 数据框构建二维数组

python-3.x - Pandas 分析错误 AttributeError : 'DataFrame' object has no attribute 'profile_report'

python - 如何为 Django/Mezzanine 站点的管理员设置权限

python - Django 和 MVC(MVT) 布局

python - 在 CSS 中使用 Django 标记