squidvision
squidvision

Reputation: 289

Changing the value of elements in a series of a dataframe python

I want to change a dollar amount, which is read as a string, into a float. Below is an excerpt of the dataframe's series. I want to strip the dollar sign and convert the values into floats. What's the best way to do this?

0          $0 
1    $186,800 
2     $87,600 
3    $139,200 
4    $168,100 
Name: DemMedHomeValue, dtype: object
0         $0 
1         $0 
2    $38,750 
3    $38,942 
4    $71,509 
Name: DemMedIncome, dtype: object

Upvotes: 1

Views: 58

Answers (1)

jezrael
jezrael

Reputation: 862651

Use str.strip for remove $, str.replace and astype for casting to float:

print df
  DemMedHomeValue
0              $0
1        $186,800
2         $87,600
3        $139,200
4        $168,100

df['DemMedHomeValue'] = df['DemMedHomeValue'].str.strip('$')
                                             .str.replace(',', '.')
                                             .astype(float)
print df
   DemMedHomeValue
0              0.0
1            186.8
2             87.6
3            139.2
4            168.1

Upvotes: 2

Related Questions