gpt4 book ai didi

python - 我正在尝试使用 Python 2 将列 str 转换为数据框中的 float

转载 作者:搜寻专家 更新时间:2023-10-30 23:27:44 26 4
gpt4 key购买 nike

我是数据分析的新手,正在寻求帮助。我正在使用 python 从头开始​​创建我的 Knn 算法。我需要将我的数据帧的其中一列(str 转换为 float)。我正在使用 python 2。这就是数据框的样子。

    sepal_length  sepal_width  petal_length  petal_width CLASS_LABEL
0 6.1 2.9 4.7 1.4 versicolor
1 6.0 2.7 5.1 1.6 versicolor
2 5.4 3.0 4.5 1.5 versicolor
3 5.6 2.5 3.9 1.1 versicolor

我必须将 CLASS_LABEL 列 str 转换为 float 。提前致谢!

from scipy.io import arff
from io import StringIO
import scipy
import pandas as pd
import numpy as np
import math
train,meta = arff.loadarff(open('train.arff', 'r'))
train = pd.DataFrame(train)
print(train)
print(type(train))
train.CLASS_LABEL = train.CLASS_LABEL.astype('float64')
print(train['CLASS_LABEL'])

-------------------------------------------- ------------------------------

 ValueError                                Traceback (most recent call last)
<ipython-input-133-9b34833d2225> in <module>()
2 # train.head()
3 # print(type(train))
----> 4 train.CLASS_LABEL = train.CLASS_LABEL.astype('float64')
5 print(train['CLASS_LABEL'])

/anaconda2/lib/python2.7/site-packages/pandas/util/_decorators.pyc in wrapper(*args, **kwargs)
176 else:
177 kwargs[new_arg_name] = new_arg_value
--> 178 return func(*args, **kwargs)
179 return wrapper
180 return _deprecate_kwarg

/anaconda2/lib/python2.7/site-packages/pandas/core/generic.pyc in astype(self, dtype, copy, errors, **kwargs)
4999 # else, only a single dtype is given
5000 new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors,
-> 5001 **kwargs)
5002 return self._constructor(new_data).__finalize__(self)
5003

/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in astype(self, dtype, **kwargs)
3712
3713 def astype(self, dtype, **kwargs):
-> 3714 return self.apply('astype', dtype=dtype, **kwargs)
3715
3716 def convert(self, **kwargs):

/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in apply(self, f, axes, filter, do_integrity_check, consolidate, **kwargs)
3579
3580 kwargs['mgr'] = self
-> 3581 applied = getattr(b, f)(**kwargs)
3582 result_blocks = _extend_blocks(applied, result_blocks)
3583

/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in astype(self, dtype, copy, errors, values, **kwargs)
573 def astype(self, dtype, copy=False, errors='raise', values=None, **kwargs):
574 return self._astype(dtype, copy=copy, errors=errors, values=values,
--> 575 **kwargs)
576
577 def _astype(self, dtype, copy=False, errors='raise', values=None,

/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in _astype(self, dtype, copy, errors, values, klass, mgr, **kwargs)
662
663 # _astype_nansafe works fine with 1-d only
--> 664 values = astype_nansafe(values.ravel(), dtype, copy=True)
665 values = values.reshape(self.shape)
666

/anaconda2/lib/python2.7/site-packages/pandas/core/dtypes/cast.pyc in astype_nansafe(arr, dtype, copy)
728
729 if copy:
--> 730 return arr.astype(dtype, copy=True)
731 return arr.view(dtype)
732

ValueError: could not convert string to float: setosa

最佳答案

出现错误的原因是您试图将字符串(如 setosa)转换为 float ,这显然是不可能的,因为那不是数字。

如果您想将字符串类别映射为数字,您可以使用:

train["CLASS_LABEL"] = train["CLASS_LABEL"].factorize()[0]

这会将您的字符串变成数字类别

关于python - 我正在尝试使用 Python 2 将列 str 转换为数据框中的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54269822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com