Python convert object to float

后端 未结 1 1810
执念已碎
执念已碎 2021-02-13 07:07

I read some weather data from a csv file as a dataframe named \"weather\". The problem is that one of the columns\' data type is an object. this is weird beacuse it indicates te

相关标签:
1条回答
  • 2021-02-13 07:34
    • You can use pandas.Series.astype
    • You can do something like this :

      weather["Temp"] = weather.Temp.astype(float)
      
    • You can also use pd.to_numeric that will convert the column from object to float

    • For details on how to use it checkout this link :http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html
    • Example :

      s = pd.Series(['apple', '1.0', '2', -3])
      print(pd.to_numeric(s, errors='ignore'))
      print("=========================")
      print(pd.to_numeric(s, errors='coerce'))
      
    • Output:

      0    apple
      1      1.0
      2        2
      3       -3
      =========================
      dtype: object
      0    NaN
      1    1.0
      2    2.0
      3   -3.0
      dtype: float64
      
    • In your case you can do something like this:

      weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
      
    • Other option is to use convert_objects
    • Example is as follows

      >> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
      
      0     1
      1     2
      2     3
      3     4
      4   NaN
      dtype: float64
      
    • You can use this as follows:

      weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
      
    • I have showed you examples because if any of your column won't have a number then it will be converted to NaN... so be careful while using it.
    0 讨论(0)
提交回复
热议问题