python - Python将对象转换为 float

标签 python pandas

我从csv文件中读取了一些天气数据,将其作为一个名为“天气”的数据框。问题在于列的数据类型之一是对象。这很奇怪,因为它表明温度...无论如何,如何将其更改为浮点型?我尝试了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

最佳答案

您可以使用pandas.Series.astype
您可以执行以下操作:

weather["Temp"] = weather.Temp.astype(float)

您还可以使用pd.to_numeric将列从对象转换为浮点
有关如何使用它的详细信息,请查看此链接:http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html
范例:

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 ...,因此在使用它时要小心。

关于python - Python将对象转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48094854/

相关文章:

python - 如何知道是否发生欠拟合或过拟合?

python - 我想使用用户在一个屏幕上在其他屏幕上输入的文本作为标题(按钮或标签)

python - 如何在C++中将Python字符串转换为其转义版本?

python - python 中的 Zip 运算符

python - Pandas:检查另一列中是否存在子字符串,然后创建一个具有特定值的新列

python - 与空 DataFrame 合并

python - 在 python 中,是否可以使用单个命令更新或初始化字典键?

python - Pandas 多索引切片 "Level type mismatch"

python - 如果您知道使用 pandas 数据框的列值和行值,如何检索数据?

python - 如何在python中对嵌套字典进行排序?