Bri*_*n L 2 python excel pandas python-applymap
我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
Run Code Online (Sandbox Code Playgroud)
帐户年龄代表我在帐户上拥有此帐户的时间。也许我想将负收入单元标记为红色。我可以:
def color_neg_revenue(val):
if val < 0:
color = 'red'
return "background-color: %s" % color
df = df.style.applymap(color_neg_revenue, subset=["Revenue"])
Run Code Online (Sandbox Code Playgroud)
我可以将其导出到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"])
Run Code Online (Sandbox Code Playgroud)
我得到:
AttributeError: 'Styler' object has no attribute 'style'
Run Code Online (Sandbox Code Playgroud)
为什么不能applymap()在已经使用过的数据帧上使用applymap()?我该如何解决?
问题不在于功能。在您的第一个电话中,您执行:
df = df.style.applymap(color_neg_revenue, subset=["Revenue"])Run Code Online (Sandbox Code Playgroud)
因此,现在df不再是DataFrame,而是一个Styler。这样Styler当然有没有.style属性了。因此,最好将其分配给另一个变量,并在该变量上进行链接。喜欢:
s = df.style.applymap(color_neg_revenue, subset=["Revenue"])
# Look mom, no I have no .style
s = s.applymap(color_new_account, subset=["AccountAge"])Run Code Online (Sandbox Code Playgroud)
因此,当您使用时,可以链接此类applymap调用Styler,但此类样式器.style本身没有属性。