Converting strings to floats in a DataFrame

前端 未结 6 848
无人及你
无人及你 2020-11-27 12:30

How to covert a DataFrame column containing strings and NaN values to floats. And there is another column whose values are strings and floats; how to convert th

6条回答
  •  情话喂你
    2020-11-27 12:56

    NOTE: pd.convert_objects has now been deprecated. You should use pd.Series.astype(float) or pd.to_numeric as described in other answers.

    This is available in 0.11. Forces conversion (or set's to nan) This will work even when astype will fail; its also series by series so it won't convert say a complete string column

    In [10]: df = DataFrame(dict(A = Series(['1.0','1']), B = Series(['1.0','foo'])))
    
    In [11]: df
    Out[11]: 
         A    B
    0  1.0  1.0
    1    1  foo
    
    In [12]: df.dtypes
    Out[12]: 
    A    object
    B    object
    dtype: object
    
    In [13]: df.convert_objects(convert_numeric=True)
    Out[13]: 
       A   B
    0  1   1
    1  1 NaN
    
    In [14]: df.convert_objects(convert_numeric=True).dtypes
    Out[14]: 
    A    float64
    B    float64
    dtype: object
    

提交回复
热议问题