[英]Pandas get_dummies generates multiple columns for the same feature
我正在使用熊猫系列,并尝试将其转换为一种热门编码。 我使用describe
方法来检查系列有多少个独特类别。 输出为:
input['pattern'].describe(include='all')
count 9725
unique 7
top 1
freq 4580
Name: pattern, dtype: object
当我尝试时:
x = pd.get_dummies(input['pattern'])
x.describe(include= 'all')
我得到18个班级,其中12个班级完全为零。 为什么get_dummies
产生了即使在输入中也没有出现过的类?
从评论的讨论中,可以推断出您的列包含字符串和整数的混合。
例如,
s = pd.Series(['0', 0, '0', '6', 6, '6', '3', '3'])
s
0 0
1 0
2 0
3 6
4 6
5 6
6 3
7 3
dtype: object
现在,调用pd.get_dummies
将导致具有相同功能的多个此类列。
pd.get_dummies(s)
0 6 0 3 6
0 0 0 1 0 0
1 1 0 0 0 0
2 0 0 1 0 0
3 0 0 0 0 1
4 0 1 0 0 0
5 0 0 0 0 1
6 0 0 0 1 0
7 0 0 0 1 0
解决方法是确保所有元素都属于同一类型。 对于这种情况,我建议将其转换为str
。
s.astype(str).str.get_dummies()
0 3 6
0 1 0 0
1 1 0 0
2 1 0 0
3 0 0 1
4 0 0 1
5 0 0 1
6 0 1 0
7 0 1 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.