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

前端 未结 3 508
慢半拍i
慢半拍i 2020-12-12 03:30

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

With below code i couldnt remove the $ sign.

input:

df[:] = df[         


        
相关标签:
3条回答
  • 2020-12-12 03:52

    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)
    
    0 讨论(0)
  • 2020-12-12 04:06

    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
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
提交回复
热议问题