这是我的数据框架
c2_name Q1_GMV Q2_GMV growth(%)
0 A 1170727260 221801763 -81
1 B 1604716749 829186592 -48
2 C 661473481 553698141 -16我尝试使用pandas样式将CSS添加到数据帧输出中。
# Set colormap equal to seaborns light green color palette
cm = sns.light_palette("green", as_cmap=True)
(df.style
.background_gradient(cmap=cm, subset=['growth(%)'])
.set_caption('This is a custom caption.')
.set_table_styles(styles))但是得到这个错误
TypeError: ("unsupported operand type(s) for -: 'decimal.Decimal' and 'float'", 'occurred at index growth(%)')试着让它看起来像这样
发布于 2018-06-21 21:33:06
你使用Decimal而不是float有什么特别的原因吗?这似乎是你问题的根源。在上面的示例中,给定列中的值,这是完全不必要的。您可以通过以下方式解决您的问题:
df['growth(%)'] = df['growth(%)'].astype('float')示例:
from decimal import Decimal
import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)
print(df)
# c2_name Q1_GMV Q2_GMV growth(%)
#0 A 1170727260 221801763 -81.0
#1 B 1604716749 829186592 -48.0
#2 C 661473481 553698141 -16.0
df.dtypes
#c2_name object
#Q1_GMV int64
#Q2_GMV int64
#growth(%) float64
#Add a decimal type to the `df` to reproduce your error.
df.loc[2, 'growth(%)'] = Decimal(2.1511231)
# Now styling will throw an error:
(df.style
.background_gradient(cmap=cm, subset=['growth(%)'])
.set_caption('This is a custom caption.'))TypeError:(“-不支持的操作数类型:'decimal.Decimal‘和'float'",’索引增长时出现(%)‘)
# Make the Decimals into floats
df['growth(%)'] = df['growth(%)'].astype('float')
(df.style
.background_gradient(cmap=cm, subset=['growth(%)'])
.set_caption('This is a custom caption.'))

如果需要保留Decimal类型,可以考虑编写一个仅转换该类型以进行样式和显示的函数。
https://stackoverflow.com/questions/50966174
复制相似问题