numpy将分类字符串数组转换为整数数组
我正在尝试把一个包含分类变量的字符串数组转换成一个包含分类变量的整数数组。
比如:
import numpy as np
a = np.array( ['a', 'b', 'c', 'a', 'b', 'c'])
print a.dtype
>>> |S1
b = np.unique(a)
print b
>>> ['a' 'b' 'c']
c = a.desired_function(b)
print c, c.dtype
>>> [1,2,3,1,2,3] int32
我知道这可以通过循环来实现,但我想应该有更简单的方法。谢谢。
9 个回答
37
……几年后……
为了完整性(因为在答案中没有提到这一点)和个人原因(我在我的模块中总是导入pandas
,但不一定会导入sklearn
),使用pandas.get_dummies()
也非常简单。
import numpy as np
import pandas
In [1]: a = np.array(['a', 'b', 'c', 'a', 'b', 'c'])
In [2]: b = pandas.get_dummies(a)
In [3]: b
Out[3]:
a b c
0 1 0 0
1 0 1 0
2 0 0 1
3 1 0 0
4 0 1 0
5 0 0 1
In [3]: b.values.argmax(1)
Out[4]: array([0, 1, 2, 0, 1, 2])
71
np.unique 有一些可选的返回值
其中 return_inverse 会返回整数编码,我经常用到这个
>>> b, c = np.unique(a, return_inverse=True)
>>> b
array(['a', 'b', 'c'],
dtype='|S1')
>>> c
array([0, 1, 2, 0, 1, 2])
>>> c+1
array([1, 2, 3, 1, 2, 3])
它可以用来从唯一值中重新创建原始数组
>>> b[c]
array(['a', 'b', 'c', 'a', 'b', 'c'],
dtype='|S1')
>>> (b[c] == a).all()
True
1
嗯,这个方法有点小聪明……但是它真的有用吗?
In [72]: c=(a.view(np.ubyte)-96).astype('int32')
In [73]: print(c,c.dtype)
(array([1, 2, 3, 1, 2, 3]), dtype('int32'))