0

I have a dataframe column price which has a value like $783024.20... This is a string with datatype as object..

test =
 0.  price
 1. '$783024.20'

dtype = object


    test['price'].astype(float)

getting an error:

could not convert string to float: '$783024.20'

what can I do for this, as I thought this would work?

Werner Hertzog
  • 2,002
  • 3
  • 24
  • 36
karan
  • 309
  • 2
  • 10
  • 1
    Why should it work? `float('$1.23')` doesn't work. – hpaulj Nov 13 '20 at 16:41
  • There is no reason `str` can be cast to `float` just because `$` should mean "dollar". In any case, there is already a thread about pandas and currency in SO https://stackoverflow.com/questions/29535163/what-dtype-to-use-for-money-representation-in-pandas-dataframe – ClementWalter Nov 13 '20 at 16:46
  • 1
    for your problem you can simply do `df.price.astype(str).str.replace("$", "").astype(float)` and it should work – ClementWalter Nov 13 '20 at 16:48
  • I've been trying to remove dollar sign but it wasn't reading it.. Thanks for the answers.. Thanks @ClementWalter.. :) – karan Nov 13 '20 at 16:52
  • Have you tried test['price'].str.slice(start=1).astype(float) or test['price'].str.extract(r'\$(\d*\.\d*)').astype(float)? You might have to play around with the regex a bit depending on what's in your column. – Linden Nov 19 '20 at 12:00

0 Answers0