2

I have the following dataframe:

df2 = pd.DataFrame({'price': [Decimal(1.4334), Decimal(1.4335), Decimal(1.4336), Decimal(1.4337)], 'tpo_count': [1, 2, 3, 1], 'tpo': ['A', 'BC', 'BCD', 'D']})
print(df2.dtypes)

price        object
tpo_count     int64
tpo          object
dtype: object

If want ot create an additional column named "price_float" which is the same column as "price" but with floats (to be later draw using matplotlib which does not support Decimal).

I have tried:

df2['price_float']=float(df2['price'])

but I get:

TypeError: cannot convert the series to <class 'float'>
2
  • 3
    df2['price_float'] = df2['price_float'].astype(float). Did you actually try researching how to change types? Commented Aug 11, 2019 at 13:47
  • This is the way to go as @roganjosh said. Commented Aug 11, 2019 at 15:42

2 Answers 2

4

Just simulating your sample DataFrame:

Sample DataFarme:

>>> df2
    price  tpo  tpo_count
0  1.4334    A          1
1  1.4335   BC          2
2  1.4336  BCD          3
3  1.4337    D          1
>>> print(df2.dtypes)
price        object
tpo          object
tpo_count     int64
dtype: object

Solution..

>>> df2['price_float'] = df2['price'].astype(float)
>>> df2
    price  tpo  tpo_count  price_float
0  1.4334    A          1       1.4334
1  1.4335   BC          2       1.4335
2  1.4336  BCD          3       1.4336
3  1.4337    D          1       1.4337

now you got new float column created..

>>> print(df2.dtypes)
price           object
tpo             object
tpo_count        int64
price_float    float64
dtype: object
Sign up to request clarification or add additional context in comments.

2 Comments

Will the numbers in decimal.Decimal be ALWAYS retained during conversion to float? i.e. any possible changes of values, like round up or round down?
@Gathide Decimal and float are different beasts, so yes the numbers may change very slightly, which is the whole reason for Decimal type existing in the first place. Good summary: docs.python.org/3/library/decimal.html
1

You can use astype function:

 df.astype({'col1': 'int32'}).dtypes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.