AttributeError:“列表”对象没有属性“应用”

时间:2019-06-02 22:03:36

标签: python-3.x attributeerror one-hot-encoding

我正在尝试将x编码为字符串,但会抛出属性错误

import numpy as np
x = ['jan','feb','march','april','may']
y = [[30],[40],[50],[60],[70]]

from sklearn import preprocessing 
le = preprocessing.LabelEncoder()
x_2 = x.apply(le.fit_transform)

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-32-46b170d1a888> in <module>
----> 1 x_2 = x.apply(le.fit_transform)

AttributeError: 'list' object has no attribute 'apply'

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您的变量x是一个列表。列表对象在Python中带有许多方法,但是apply不是其中之一。

根据sklearn preprocessing docs,您需要初始化labelEncoder的实例,然后使用fitfit_transform编码器类方法将其放入列表中

import numpy as np
from sklearn import preprocessing

x = ['jan','feb','march','april','may']
y = [[30],[40],[50],[60],[70]]

le = preprocessing.LabelEncoder()
le.fit_transform(x) # pass your 'x' list as an argument to the le.fit_transform() method