使用Python高亮显示基于条件的数据,并将其写回相同的.xls文件
我有一个样本数据集,我想使用Python高亮显示基于条件的数据,并将其写回相同的.xls文件,python,excel,pandas,dataframe,Python,Excel,Pandas,Dataframe,我有一个样本数据集,我想 突出显示单元格,并添加注释为“项目”列中为空/空白”的注释列 突出显示单元格,并添加一个注释列,注释为“存储”列中是否存在“\u1” 突出显示单元格并添加注释列,注释为“关键字“笔”不应标记到水果类别” 输入数据集 商场 项目 类别 储存 水果 储存 苹果_ 水果 储存 橙色 水果 储存 香蕉 水果 商店 书 固定的 B店 笔 水果 B店 铅笔 水果 B店 胶水 固定的 B店 橡皮擦 固定的 商店C 冻结的 影视 商店 巨大的 影视 商店C 铁人 影视 商店C 影视 输
import pandas as pd
import io
df = pd.read_csv(io.StringIO("""Store;Item;Category\nStore A;;Fruits\nStore A;Apple_;Fruits\nStore A;Orange;Fruits\nStore A;Banana;Fruits\nStore_B;Books;Stationary\nStore B;Pen;Fruits\nStore_B;Pencil;Fruits\nStore B;Glue;Stationary\nStore B;Eraser;Stationary\nStore C;Frozen;Movies\nStore_C;Titanic;Movies\nStore C;Iron_Man;Movies\nStore C;;Movies"""), sep=";")
我稍微修改了您的数据,以便能够高亮显示一行两次:
>>> df
Store Item Category
0 Store A NaN Fruits
1 Store A Apple_ Fruits
2 Store A Orange Fruits
3 Store A Banana Fruits
4 Store_B Books Stationary
5 Store B Pen Fruits
6 Store_B Pencil Fruits
7 Store B Glue Stationary
8 Store B Eraser Stationary
9 Store C Frozen Movies
10 Store_C Titanic Movies
11 Store C Iron_Man Movies
12 Store C NaN Movies
尝试检测错误:
comments = {"m1": "Null/Blank in Item column",
"m2": "Presence of '_' in Store column",
"m3": "Keyword 'Pen' should not tagged to Fruits category"}
# Conditions
m1 = (df["Item"].str.len() == 0) | (df["Item"].isna())
m2 = df["Store"].str.contains("_")
m3 = (df["Item"].str.startswith("Pen")) & (df["Category"].str.match("Fruits"))
dfm = pd.DataFrame({"m1": m1, "m2": m2, "m3": m3}, index=df.index)
df["Highlight Comments"] = dfm.mul(pd.DataFrame(comments, index=df.index)) \
.apply(lambda c: ', '.join(filter(bool, c)), axis="columns")
导出到excel并将样式设置为单元格:
import openpyxl as xl
with pd.ExcelWriter("output.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, index=False)
ws = writer.book.active
# convert indexes to excel cell coordinates (so ugly!)
dfm.columns = [chr(ord('A') + i) for i, _ in enumerate(dfm.columns)]
dfm.index = map(str, dfm.index + 2)
highlight = xl.styles.PatternFill(fill_type="solid", start_color="ffff00", end_color="ffff00")
for cell in dfm.unstack()[dfm.unstack()].index.map(''.join):
ws[cell].fill = highlight
请以表格形式添加数据,以便人们更容易使用。谢谢如果同一行需要高亮显示两次?是,如果条件匹配,则以黄色高亮显示该特定单元格。如果同一行有两个条件匹配,则高亮显示该行上的两个单元格。附加的输出数据集图像供参考是否更新“输出数据集”?如何填写“突出显示注释”列?是的,更新数据集并添加注释列并填写突出显示注释您测试了问题的解决方案吗?
import openpyxl as xl
with pd.ExcelWriter("output.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, index=False)
ws = writer.book.active
# convert indexes to excel cell coordinates (so ugly!)
dfm.columns = [chr(ord('A') + i) for i, _ in enumerate(dfm.columns)]
dfm.index = map(str, dfm.index + 2)
highlight = xl.styles.PatternFill(fill_type="solid", start_color="ffff00", end_color="ffff00")
for cell in dfm.unstack()[dfm.unstack()].index.map(''.join):
ws[cell].fill = highlight