Converting strings to floats in a DataFrame

前端 未结 6 807
无人及你
无人及你 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:48

    You can try df.column_name = df.column_name.astype(float). As for the NaN values, you need to specify how they should be converted, but you can use the .fillna method to do it.

    Example:

    In [12]: df
    Out[12]: 
         a    b
    0  0.1  0.2
    1  NaN  0.3
    2  0.4  0.5
    
    In [13]: df.a.values
    Out[13]: array(['0.1', nan, '0.4'], dtype=object)
    
    In [14]: df.a = df.a.astype(float).fillna(0.0)
    
    In [15]: df
    Out[15]: 
         a    b
    0  0.1  0.2
    1  0.0  0.3
    2  0.4  0.5
    
    In [16]: df.a.values
    Out[16]: array([ 0.1,  0. ,  0.4])
    

提交回复
热议问题