pandas 数据帧上的尝试除外
try-except on pandas dataframe
除了块 returns 什么都不尝试。我怎样才能解决这个问题?如果我修复了它,我怎样才能使更改永久化?
def color(val):
"""Takes a scalar and returns a string with the css
property 'bg-color:red' for negative string, black otherwise"""
color="blue" if val%2==1 else "yellow"
return f"background-color: {color}"
df = sns.load_dataset("flights")
try:
df.style.applymap(color)
except:
Exception
你可以试试:
创建 2 个独立的函数:
def color_negative(val):
cond=(val<0)
return ['color: red' if v else 'color: black' for v in cond]
def color_positive(val):
cond=(val%2==0)
return ['background-color: blue' if v else 'background-color: yellow' for v in cond]
最后:
out=df.style.apply(color_negative,subset=['passengers']).apply(color_positive,subset=['passengers'])
现在,如果您打印 out
,您将获得预期的输出
除了块 returns 什么都不尝试。我怎样才能解决这个问题?如果我修复了它,我怎样才能使更改永久化?
def color(val):
"""Takes a scalar and returns a string with the css
property 'bg-color:red' for negative string, black otherwise"""
color="blue" if val%2==1 else "yellow"
return f"background-color: {color}"
df = sns.load_dataset("flights")
try:
df.style.applymap(color)
except:
Exception
你可以试试:
创建 2 个独立的函数:
def color_negative(val):
cond=(val<0)
return ['color: red' if v else 'color: black' for v in cond]
def color_positive(val):
cond=(val%2==0)
return ['background-color: blue' if v else 'background-color: yellow' for v in cond]
最后:
out=df.style.apply(color_negative,subset=['passengers']).apply(color_positive,subset=['passengers'])
现在,如果您打印 out
,您将获得预期的输出