如何用 pandas 为空行着色并导出到 Excel 文件?

发布于 2025-01-11 07:50:51 字数 889 浏览 1 评论 0原文

我正在尝试在 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 维度,每个单元格可以包含数字(十进制)或文本,具体取决于列名称

I am trying to automate a few tasks on excel, some include setting the cells without any values in red color (empty cells in my DataFrame dimensions and not outside it), I tried the following after checking previous similar answers:

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.')

I've also tried other ways like

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)

None of which seem to work, in the console I am getting the proper values printed and I am getting an output file with the additional row enumeration from 0, but nothing is getting colored in the output excel file

My dataset in excel has x by y dimensions and each cell can contain numbers(decimal) or text depending on the column name

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞慾 2025-01-18 07:50:51

pandas 样式器 对象是一个独立于创建它的 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 并在一个函数中执行所有修改:

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)

The pandas Styler object is a separate object from the df which creates it. To write out a styled DataFrame to excel we need to use the actual Styler object not df. The easiest way to do this is to use 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)

Method chaining also works:

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

*Note: index=False ensures that the DataFrame index is not included in the output. (the "additional row enumeration from 0")


We can also use pd.ExcelWriter with the Styler in a similar way:

# 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)

As a general improvement, we can set Styles at the DataFrame level by passing axis=None to Styler.apply and performing all modifications in one function:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文