Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: ("unsupported operand type(s) for -: 'decimal.Decimal' and 'float'", 'occurred at index growth(%)')

This is my dataframe --

    c2_name Q1_GMV      Q2_GMV     growth(%)
0   A       1170727260  221801763   -81
1   B       1604716749  829186592   -48
2   C       661473481   553698141   -16

I've trying to add CSS to the dataframe output using the pandas styling.

# 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))

But getting this error

TypeError: ("unsupported operand type(s) for -: 'decimal.Decimal' and 'float'", 'occurred at index growth(%)')

Trying to make it look something like this

here

like image 944
Naman Doshi Avatar asked Jun 21 '18 10:06

Naman Doshi


People also ask

How do I fix unsupported operand type in Python?

The Python "TypeError: unsupported operand type(s) for /: 'str' and 'int'" occurs when we try to use the division / operator with a string and a number. To solve the error, convert the string to an int or a float , e.g. int(my_str) / my_num .

What is floating decimal format?

Definition of floating decimal : a system of decimal point placement in an electronic calculator in which the decimal point is free to move automatically across the display in order to allow the maximum number of decimal places in the readout.


1 Answers

Is there a particular reason you are using Decimal instead of float? That seems to be the root of your problem. In your above example, it's totally unnecessary given the values in that column. You can solve your problem with:

df['growth(%)'] = df['growth(%)'].astype('float')

Example:

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'", 'occurred at index growth(%)')

# 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.'))

enter image description here

If you need to keep the Decimal type, consider writing a function that just converts the type for styling and display.

like image 77
ALollz Avatar answered Oct 07 '22 19:10

ALollz