如何基于Lane列值动态为DataFrame所有行上色并保留样式到Excel
按Lane列动态设置行背景色并导出带样式的Excel
实现步骤及代码
- 先安装所需依赖库:
pip install pandas openpyxl
- 定义行样式函数,根据Lane值分配对应背景色:
import pandas as pd def color_rows(row): # 为不同Lane值设置不同背景色 if row['Lane'] == '1': return ['background-color: #cce5ff'] * len(row) elif row['Lane'] == '2': return ['background-color: #d4edda'] * len(row) elif row['Lane'] == '3': return ['background-color: #fff3cd'] * len(row) # 其他Lane值保持无样式 return [''] * len(row)
- 创建DataFrame并应用样式,最后导出到Excel:
# 创建目标DataFrame df = pd.DataFrame({'Sample': ['A', 'B', 'C', 'D','E','F'], 'NFW': [8.16, 8.63, 9.25, 8.97, 7.5, 8.21], 'Qubit': [55, 100, 229, 30, 42, 33], 'Lane': ['1', '1', '2', '2', '3', '3']}) # 按行应用样式 styled_df = df.style.apply(color_rows, axis=1) # 导出带样式的Excel文件 styled_df.to_excel('styled_sample.xlsx', engine='openpyxl', index=False)
说明
color_rows函数会为每行生成与列数匹配的样式列表,确保整行应用背景色- 使用
openpyxl作为导出引擎,因为它支持保留Pandas Styler生成的样式 - 可自行替换十六进制颜色码,自定义不同Lane对应的背景色
内容的提问来源于stack exchange,提问作者Baran Aldemir
相关产品推荐
相关产品推荐

