如何用 pandas 为空行着色并导出到 Excel 文件?
我正在尝试在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
pandas 样式器 对象是一个独立于创建它的 df 的对象。要将样式化的 DataFrame 写入 Excel,我们需要使用实际的 Styler 对象而不是 df。最简单的方法是使用 Styler.to_excel:
方法链接也有效:
*注意:
index=False
确保 DataFrame 索引不包含在输出中。 (“从 0 开始的附加行枚举”)我们还可以使用 pd.ExcelWriter 与 Styler 类似方式:
作为一般改进,我们可以通过将
axis=None
传递给 Styler.apply 并在一个函数中执行所有修改: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 notdf
. The easiest way to do this is to use Styler.to_excel:Method chaining also works:
*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:
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: