首页 > 解决方案 > 使用 Python Pandas 根据条件突出显示数据并将其写回相同的 .xls 文件

问题描述

我有一个示例数据集,我想

  1. 突出显示单元格并添加注释列,其中注释“'Item' 列中的 Null/Blank”
  2. 突出显示该单元格并添加一个注释列,其中包含注释“'Store' 列中存在'_'”
  3. 突出显示该单元格并添加一个注释列,其中包含注释“关键字‘钢笔’不应标记为水果类别”

输入数据集

店铺 物品 类别
A店 水果
A店 苹果_ 水果
A店 橙子 水果
A店 香蕉 水果
商店_B 图书 固定式
B店 水果
B店 铅笔 水果
B店 胶水 固定式
B店 橡皮 固定式
C店 冷冻 电影
商店_C 泰坦尼克号 电影
C店 钢铁侠 电影
C店 电影

输入数据集

输出数据集

输出数据集

谢谢

标签: pythonexcelpandasdataframe

解决方案


输入数据:

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")
>>> df["Highlight Comments"]
0                                                               Null/Blank in Item column
1
2
3
4                                                         Presence of '_' in Store column
5                                      Keyword 'Pen' should not tagged to Fruits category
6     Presence of '_' in Store column, Keyword 'Pen' should not tagged to Fruits category
7
8
9
10                                                        Presence of '_' in Store column
11
12                                                              Null/Blank in Item column
Name: Highlight Comments, dtype: object

导出到 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

推荐阅读