我使用 Pandas Dataframe 创建了一个数据集,其中有两列,其中一列具有从另一个数据集自动生成的各种十六进制颜色代码。我想检查十六进制颜色输入是否符合预期,因此能够使用提供的十六进制代码填充每个单元格的颜色会很有帮助。我有几个代码需要检查,因此在导出到 Excel 之前在 Python 中自动完成此操作会很有帮助。
单元格由单元格中的十六进制颜色填充
任何帮助将不胜感激。
我已经看过这个解决方案,但对于我想要的东西来说它似乎太通用了在 Pandas 中给单元格着色
这个解决方案最接近我所追求的,但 applymap 似乎已经贬值,所以我无法让它工作 Python - 按单元格中的十六进制值对 DF 单元格着色
似乎没有用于从 Pandas 样式直接转换为 Excel 样式的 API。因此,我建议在将数据框转换为 Excel 对象后应用颜色格式。这可以使用 Pythonic Excel API 在内存中完成 - 我在下面的示例代码中选择了
openpyxl
。
import io
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
# Part 1: Pandas DataFrame -> Openpyxl Workbook (in-memory)
# source df
df = pd.read_csv(io.StringIO("""
hex1 hex2
0 #dcddde #ffba00
1 #954eff #b889ff
"""), sep=r"\s{2,}", engine="python")
# columns to be colored - please assign manually if irrelevant columns exist
hex_cols = df.columns.to_list()
#hex_cols = [f"hex{i}" for i in range(1, 1 + 2)]
# DataFrame -> I/O buffer
buffer = io.BytesIO()
with pd.ExcelWriter(buffer) as writer:
df.to_excel(writer)
# I/O buffer -> Workbook
wb = load_workbook(buffer)
#del buffer
# Part 2: Apply background color
ws = wb["Sheet1"]
for hex_col in hex_cols:
# locate the associated column index for the hex-color column
for col_idx, cell in enumerate(ws["1:1"]):
if cell.value == hex_col:
col_idx += 1 # convert to 1-based index
break
else:
raise ValueError("hex column name not found")
# apply background color cell-by-cell
for row_idx in range(2, 1 + ws.max_row):
cell = ws.cell(row_idx, col_idx)
color = cell.value[1:] # remove leading "#" character
# print(color)
cell.fill = PatternFill(start_color=color, end_color=color, fill_type="solid")
# optional additional styling
for cell in ws['A'] + ws[1]:
cell.style = 'Pandas'
# final output
wb.save("test.xlsx")
test.xlsx
在 LibreOffice 中打开
Python
(来自conda
):3.12.2
Pandas
:2.1.4
Openpyxl
:3.0.10OS
:Debian 12 (x86-64)