numpy 将分类字符串数组转换为整数数组 [英] numpy convert categorical string arrays to an integer array

查看:44
本文介绍了numpy 将分类字符串数组转换为整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将分类变量的字符串数组转换为分类变量的整数数组.

I'm trying to convert a string array of categorical variables to an integer array of categorical variables.

例如

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

我意识到这可以通过循环来完成,但我想有一种更简单的方法.谢谢.

I realize this can be done with a loop but I imagine there is an easier way. Thanks.

推荐答案

好吧,这是一个 hack ......但它有帮助吗?

Well, this is a hack... but does it help?

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'))

这篇关于numpy 将分类字符串数组转换为整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆