【发布时间】:2018-12-18 17:56:04
【问题描述】:
我正在使用df.to_excel() 将数据从 pandas 数据框输出到 Excel。为了提高可读性,我使用df.style.applymap() 根据内容更改单元格的颜色。
假设我有一个看起来像这样的数据框:
df =
Account Revenue AccountAge
0 "Boeing" 5000 5.6
1 "Lockheed" -10000 1.2
2 "Airbus" 12000 0.6
3 "Northrop" -3000 8.4
帐户年龄表示我在账簿上拥有此帐户的时间。也许我想将负收入单元格标记为红色。我能做到:
def color_neg_revenue(val):
if val < 0:
color = 'red'
return "background-color: %s" % color
df = df.style.applymap(color_neg_revenue, subset=["Revenue"])
我可以将它导出到 excel 中,而且格式看起来很棒!但是假设我也想在尝试时将新帐户标记为黄色:
def color_new_account(val):
if val < 3:
color = 'yellow'
return "background-color: %s" % color
df = df.style.applymap(color_new_account, subset=["AccountAge"])
我明白了:
AttributeError: 'Styler' object has no attribute 'style'
为什么我不能在我已经使用过applymap() 的数据帧上使用applymap()?我该如何解决这个问题?
【问题讨论】:
-
但是您将样式器分配给
df。
标签: python excel pandas python-applymap