Python将对象转换为float

Alm*_*erg 6 python pandas

我从csv文件中读取了一些天气数据作为名为"weather"的数据帧.问题是列的数据类型之一是一个对象.这是奇怪的,因为它表示温度......无论如何,如何将其更改为浮点数?我试过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
Run Code Online (Sandbox Code Playgroud)

Jai*_*Jai 17


Alm*_*erg 5

我最终使用了:

weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)
Run Code Online (Sandbox Code Playgroud)

它工作得很好,除了我收到以下消息。

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.
Run Code Online (Sandbox Code Playgroud)

  • 警告:convert_objects 已弃用 (3认同)

Muh*_*man 5

我尝试了这里建议的所有方法,但遗憾的是都没有奏效。相反,发现这是有效的:

df['column'] = pd.to_numeric(df['column'],errors = 'coerce')
Run Code Online (Sandbox Code Playgroud)

然后使用以下方法检查它:

print(df.info())
Run Code Online (Sandbox Code Playgroud)