我尝试在一个大型pandas数据帧中对包含分类数据("Yes"
和"No"
)的多个列进行编码。完整的数据帧包含400多列,因此我在寻找一种方法来编码所有所需的列,而不必逐个编码。我使用Scikit-learn LabelEncoder
对分类数据进行编码。
数据帧的第一部分不一定要编码,但是我正在寻找一种方法来直接编码包含分类日期的所有所需列,而不拆分和连接数据帧。
为了演示我的问题,我首先尝试在数据帧的一小部分上解决它。然而,停留在数据拟合和转换的最后部分,并获得一个ValueError: bad input shape (4,3)
。我运行时的代码如下:
# Create a simple dataframe resembling large dataframe
data = pd.DataFrame({'A': [1, 2, 3, 4],
'B': ["Yes", "No", "Yes", "Yes"],
'C': ["Yes", "No", "No", "Yes"],
'D': ["No", "Yes", "No", "Yes"]})
# Import required module
from sklearn.preprocessing import LabelEncoder
# Create an object of the label encoder class
labelencoder = LabelEncoder()
# Apply labelencoder object on columns
labelencoder.fit_transform(data.ix[:, 1:]) # First column does not need to be encoded
完整的错误报告:
labelencoder.fit_transform(data.ix[:, 1:])
Traceback (most recent call last):
File "<ipython-input-47-b4986a719976>", line 1, in <module>
labelencoder.fit_transform(data.ix[:, 1:])
File "C:\Anaconda\Anaconda3\lib\site-packages\sklearn\preprocessing\label.py", line 129, in fit_transform
y = column_or_1d(y, warn=True)
File "C:\Anaconda\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 562, in column_or_1d
raise ValueError("bad input shape {0}".format(shape))
ValueError: bad input shape (4, 3)
有人知道怎么做吗?
发布于 2017-09-19 02:36:54
如下代码所示,您可以通过对DataFrame应用LabelEncoder
对多个列进行编码。但是,请注意,我们无法获得所有列的类信息。
import pandas as pd
from sklearn.preprocessing import LabelEncoder
df = pd.DataFrame({'A': [1, 2, 3, 4],
'B': ["Yes", "No", "Yes", "Yes"],
'C': ["Yes", "No", "No", "Yes"],
'D': ["No", "Yes", "No", "Yes"]})
print(df)
# A B C D
# 0 1 Yes Yes No
# 1 2 No No Yes
# 2 3 Yes No No
# 3 4 Yes Yes Yes
# LabelEncoder
le = LabelEncoder()
# apply "le.fit_transform"
df_encoded = df.apply(le.fit_transform)
print(df_encoded)
# A B C D
# 0 0 1 1 0
# 1 1 0 0 1
# 2 2 1 0 0
# 3 3 1 1 1
# Note: we cannot obtain the classes information for all columns.
print(le.classes_)
# ['No' 'Yes']
发布于 2020-04-27 15:52:03
首先,找出类型为object的所有功能:
objList = all_data.select_dtypes(include = "object").columns
print (objList)
现在,要将上面的objList特性转换为数字类型,您可以使用forloop,如下所示:
#Label Encoding for object to numeric conversion
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
for feat in objList:
df[feat] = le.fit_transform(df[feat].astype(str))
print (df.info())
请注意,我们在forloop中显式地提到了string类型,因为如果您删除它,它会抛出一个错误。
发布于 2019-08-16 14:21:13
Scikit-learn现在有了一些东西:OrdinalEncoder
from sklearn.preprocessing import OrdinalEncoder
data = pd.DataFrame({'A': [1, 2, 3, 4],
'B': ["Yes", "No", "Yes", "Yes"],
'C': ["Yes", "No", "No", "Yes"],
'D': ["No", "Yes", "No", "Yes"]})
oe = OrdinalEncoder()
t_data = oe.fit_transform(data)
print(t_data)
# [[0. 1. 1. 0.]
# [1. 0. 0. 1.]
# [2. 1. 0. 0.]
# [3. 1. 1. 1.]]
开箱即用。
https://stackoverflow.com/questions/44474570
复制相似问题