首页 > 解决方案 > 将带有多个变量的csv单列转换为带有单个变量的多列

问题描述

我在 csv 中有多个这样的变量的列

col1
a, c, e, f
b, c, g, p
d, e, i, x

我需要把它们变成

a    b    c    d
1    0    1    0
0    1    1    0
0    0    0    1

用于机器学习预处理目的。当我尝试使用 LabelEncoder 和 OneHotEncoder 时,返回了错误的尺寸警告。

# Creating an integer encoding of labels  
label_encoder = LabelEncoder() 
integer_encoded = label_encoder.fit_transform(X)

处理这个的正确方法是什么?

标签: pythoncsvscikit-learn

解决方案


使用sklearn.feature_extraction.text.CountVectorizer

演示:

In [192]: from sklearn.feature_extraction.text import CountVectorizer

In [193]: cv = CountVectorizer(token_pattern='(?u)\\b\\w+\\b', vocabulary=list('abcd'))

In [194]: X = cv.fit_transform(df['col1'])

In [195]: X
Out[195]:
<3x4 sparse matrix of type '<class 'numpy.int64'>'
        with 5 stored elements in Compressed Sparse Row format>

In [196]: X.A
Out[196]:
array([[1, 0, 1, 0],
       [0, 1, 1, 0],
       [0, 0, 0, 1]], dtype=int64)

In [197]: cv.get_feature_names()
Out[197]: ['a', 'b', 'c', 'd']

如果我们不使用vocabulary- 我们将为每个唯一单词获得一列:

In [203]: cv = CountVectorizer(token_pattern='(?u)\\b\\w+\\b')

In [204]: X = cv.fit_transform(df['col1'])

In [205]: X.A
Out[205]:
array([[1, 0, 1, 0, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 0, 0, 0, 1, 0, 1, 0],
       [0, 0, 0, 1, 1, 0, 0, 1, 0, 1]], dtype=int64)

In [206]: cv.get_feature_names()
Out[206]: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'p', 'x']

来源 DF:

In [191]: df
Out[191]:
         col1
0  a, c, e, f
1  b, c, g, p
2  d, e, i, x

推荐阅读