Pandas 将数据类型从对象转换为浮点数

新手上路,请多包涵

我从 .csv 文件中读取了一些天气数据作为名为“天气”的数据框。问题是其中一列的数据类型是 object 。这很奇怪,因为它指示温度。如何将其更改为 float 数据类型?我试过 to_numeric ,但它无法解析它。

 weather.info()
weather.head()

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 304 entries, 2017-01-01 to 2017-10-31
Data columns (total 2 columns):
Temp    304 non-null object
Rain    304 non-null float64
dtypes: float64(1), object(1)
memory usage: 17.1+ KB

           Temp     Rain
Date
2017-01-01  12.4    0.0
2017-02-01  11      0.6
2017-03-01  10.4    0.6
2017-04-01  10.9    0.2
2017-05-01  13.2    0.0

原文由 Almog Woldenberg 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 232
1 个回答
  • 您可以使用 pandas.Series.astype
  • 你可以这样做:
   weather["Temp"] = weather.Temp.astype(float)

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

  • 输出:
   0    apple
  1      1.0
  2        2
  3       -3
  =========================
  dtype: object
  0    NaN
  1    1.0
  2    2.0
  3   -3.0
  dtype: float64

  • 在您的情况下,您可以执行以下操作:
   weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')

  • 其他选项是使用 convert_objects
  • 例子如下
  >> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)

  0     1
  1     2
  2     3
  3     4
  4   NaN
  dtype: float64

  • 您可以按如下方式使用它:
   weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)

  • 我已经向您展示了示例,因为如果您的任何列没有数字,那么它将被转换为 NaN … 所以在使用它时要小心。

原文由 Jai 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题