如何将条件格式导出到Excel fi

2024-10-03 06:22:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我已将以下条件格式应用于数据帧。不过,现在我想将数据框导出到一个Excel文件,而不丢失颜色格式。有什么想法吗?你知道吗

def highlight(ex):
    if ex.Monatsgehalt_September == 0 or ex.Bonus == 0:
        return ['color: red']*col
    else:
        return ['color: black']*col

ex.style.apply(highlight, axis=1)

Tags: 文件数据returnif颜色def格式col
2条回答

pandas文档的section解释了如何使用条件格式将数据帧导出到excel。你知道吗

下面是一个简单的例子:

import pandas as pd
import numpy as np

# Initialize example dataframe
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1)
df.iloc[0, 2] = np.nan

def highlight_max(s):
    """Styling function: highlights the maximum in a Series yellow."""
    is_max = s == s.max()
    return ['background-color: yellow' if v else '' for v in is_max]

def color_negative_red(val):
    """Styling function: apply red font color to negative values."""
    color = 'red' if val < 0 else 'black'
    return f'color: {color}'

# Apply conditional formatting to dataframe
styled = df.style.applymap(color_negative_red).apply(highlight_max)

# Export styled dataframe to excel
styled.to_excel('styled.xlsx', engine='xlsxwriter')

不能导出条件格式,但可以使用模块xlsxwriter

https://xlsxwriter.readthedocs.io/example_conditional_format.html#ex-cond-format

相关问题 更多 >