python - 将带有多个变量的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)
处理这个的正确方法是什么?
解决方案
使用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
推荐阅读
- caching - 一次性事件的浏览器存储?
- embedded - 在 Bazel Build 中导入 cmocka 库
- chart.js - 添加从点到x轴的线和他的粗体标签
- javascript - 样式组件不导出
- javascript - 在自定义下拉列表中选择“全部”选项时,如何不显示“清除过滤器”?
- javascript - 从装饰器调用函数,同时保留函数原始类的“this”上下文
- javascript - 如何在邮件中发送具有唯一 ID 的链接并检查用户是否打开它?
- angular - 从父组件传递值到子组件不起作用
- java - 嵌入式列表 Java Spring 的问题
- python - Python - Plotly - 子图中散点图顶部的指示器