okl
okl

Reputation: 317

pandas - how to convert all columns from object to float type

I trying to convert all columns with '$' amount from object to float type.

With below code i couldnt remove the $ sign.

input:

df[:] = df[df.columns.map(lambda x: x.lstrip('$'))]

Upvotes: 1

Views: 1546

Answers (3)

prabhakar
prabhakar

Reputation: 572

Please use the below regular expression based matching to replace all occurrences of $ with null character

df = df.replace({'\$': ''}, regex=True) 

UPDATE: As per @Wen suggestion, the solution will be

df.iloc[:,9:32]=df.iloc[:,9:32].replace({'\$':''},regex=True).astype(float)

Upvotes: 1

niraj
niraj

Reputation: 18208

May be you can also try using applymap:

df[:] = df.astype(str).applymap(lambda x:  x.lstrip('$')).astype(float)

If df is:

   0   1   2
0  $1  7   5
1  $2  7   9
2  $3  7   9

Then, it will result in:

    0    1    2
0  1.0  7.0  5.0
1  2.0  7.0  9.0
2  3.0  7.0  9.0

Upvotes: 1

BENY
BENY

Reputation: 323226

You can using extract

df=pd.DataFrame({'A':['$10.00','$10.00','$10.00']})
df.apply(lambda x : x.str.extract('(\d+)',expand=False).astype(float))
Out[333]: 
      A
0  10.0
1  10.0
2  10.0

Update

df.iloc[:,9:32]=df.iloc[:,9:32].apply(lambda x : x.str.extract('(\d+)',expand=False).astype(float))

Upvotes: 2

Related Questions