python将object转换为float_Python将对象转换为浮点数

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 temperature... anyway, how to I change it to a float? I tried to_numeric but it can't parse it.

weather.info()

weather.head()

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

解决方案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

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

ENJOY !!!!!!!!!!!!!! :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值