【问题标题】:How can I color the empty rows in and export to an excel file with pandas?如何使用 pandas 为空行着色并导出到 excel 文件?
【发布时间】:2022-01-19 18:49:17
【问题描述】:

我正在尝试在 excel 上自动执行一些任务,其中一些包括将单元格设置为没有任何红色值的单元格(我的 DataFrame 维度中的空单元格,而不是在它之外),我在检查了以前的类似答案后尝试了以下操作:

import pandas as pd

# Create a dataframe
df = pd.read_excel(r'input.xls', sheet_name='sheet1')
print(df)

df.style.applymap(lambda x: 'background-color : yellow' if x>1 else '')


# create excel writer object
writer = pd.ExcelWriter(r'Output.xls')

# write dataframe to excel
df.to_excel(writer)
# save the excel
writer.save()
print('DataFrame is written successfully to Excel File.')

我也尝试过其他方法,例如

def color(row):
    if row.isnull().values.any() == True:
        return ['background-color: red'] * len(row)
    return [''] * len(row)

# Apply the function
df.style.apply(color, axis=1)

这些似乎都不起作用,在控制台中我打印了正确的值,并且我得到了一个输出文件,其中包含从 0 开始的附加行枚举,但输出 excel 文件中没有任何颜色

我在 excel 中的数据集有 x x y 维度,每个单元格可以包含数字(十进制)或文本,具体取决于列名

【问题讨论】:

    标签: python excel pandas dataframe pandas-styles


    【解决方案1】:

    pandas Styler 对象是独立于创建它的 df 的对象。要将样式化的 DataFrame 写入 excel,我们需要使用实际的 Styler 对象,而不是 df。最简单的方法是使用Styler.to_excel

    # Save Styler Object for Later
    styler = df.style
    # Apply Styles (This can be chained or on separate lines)
    styler.applymap(lambda x: 'background-color : yellow' if x > 1 else '')
    styler.apply(color, axis=1)
    # Export the styler to excel
    styler.to_excel('Output.xls', index=False)
    

    方法链也可以:

    df.style \
        .applymap(lambda x: 'background-color : yellow' if x > 1 else '') \
        .apply(color, axis=1) \
        .to_excel('Output.xls', index=False)
    

    *注意:index=False 确保输出中不包含 DataFrame 索引。 (“从 0 开始的附加行枚举”)


    我们也可以以类似的方式将pd.ExcelWriterStyler 一起使用:

    # Save Styler Object for Later
    styler = df.style
    # Apply Styles (This can be chained or on separate lines)
    styler.applymap(lambda x: 'background-color : yellow' if x > 1 else '')
    styler.apply(color, axis=1)
    
    with pd.ExcelWriter('Output.xls') as writer:
        styler.to_excel(writer, index=False)
    

    作为一项总体改进,我们可以通过将axis=None 传递给Styler.apply 并在一个函数中执行所有修改来在DataFrame 级别设置样式:

    def color(df_):
        styles_df = pd.DataFrame('', index=df_.index, columns=df_.columns)
        # Color cells yellow where they are greater than 1
        styles_df[df_ > 1] = 'background-color: yellow'
        # Color rows red where there are any null values across rows
        styles_df.loc[df.isnull().any(axis=1), :] = 'background-color: red'
        return styles_df
    
    
    with pd.ExcelWriter('Output.xls') as writer:
        df.style.apply(color, axis=None).to_excel(writer, index=False)
    

    【讨论】:

    • 谢谢,现在他们正在着色,但当我将条件设置为 styler.applymap(lambda x: 'background-color : yellow' if x ==None else '') 它时面临一个奇怪的问题没有给任何东西上色,当我把它设置为 x==0 时,它甚至给文本 False 上色,但没有给任何空单元格上色
    • 所以这更像是一个与实际 pandas 样式无关的一般 python 逻辑问题。 == None 不太可能给出预期的结果,尤其是在 pandas 中,具有各种不同的方式可以存储类似 None 的数据。此外,听起来您有一个布尔列。在 python 中,False == 0 的计算结果为 True,这就是它被着色的原因。
    • 如果您需要基于特定样式规则的特定样式的帮助,您可以将一个新问题与示例 DataFrame df = pd.DataFrame({... sample data ...}) 放在一起,然后解释它应该如何设置样式。有人可能会帮助您适当地定义样式规则。
    猜你喜欢
    • 2020-01-01
    • 2014-05-03
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 2011-01-01
    相关资源
    最近更新 更多