【问题标题】:TypeError: ("unsupported operand type(s) for -: 'decimal.Decimal' and 'float'", 'occurred at index growth(%)')TypeError: ("unsupported operand type(s) for -: 'decimal.Decimal' and 'float'", 'occurred at index growth(%)')
【发布时间】:2018-11-30 15:31:35
【问题描述】:

这是我的数据框 --

    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(%)')

试图让它看起来像这样

here

【问题讨论】:

    标签: pandas jupyter-notebook styling pandas-styles


    【解决方案1】:

    您使用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: ("unsupported operand type(s) for -: 'decimal.Decimal' and '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 类型,请考虑编写一个仅转换类型以进行样式设置和显示的函数。

    【讨论】:

    • 谢谢,它成功了。我可以得到渐变颜色的降序版本,使得最大的负值是深绿色等等?
    • @NamanDoshi 使用reverse=Truecm = sns.light_palette("green", as_cmap=True, reverse=True) 定义颜色图时
    猜你喜欢
    • 2020-10-01
    • 2017-07-17
    • 2021-09-12
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2023-04-02
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多