Python 2.7,numpy,以因子列表的形式创建级别。

我有一个列出自变量的数据文件,最后一列表示类。例如:

2.34,4.23,0.001, ... ,56.44,2.0,"cloudy with a chance of rain"

使用 numpy,我将所有数字列读入一个矩阵,并将最后一列读入一个我称之为“类”的数组。事实上,我事先不知道类名,所以我不想使用字典。我也不想使用 Pandas。下面是问题的一个例子:
classes = ['a', 'b', 'c', 'c', 'b', 'a', 'a', 'd']
type (classes)
<type 'list'>
classes = numpy.array(classes)
type(classes)
<type 'numpy.ndarray'>
classes
array(['a', 'b', 'c', 'c', 'b', 'a', 'a', 'd'],
      dtype='|S1')
# requirements call for a list like this:
# [0, 1, 2, 2, 1, 0, 3]

请注意,目标类可能非常稀疏,例如,“z”可能是 100,000 例中的​​ 1 例。另请注意,类可以是任意的文本字符串,例如科学名称。

我正在使用带有 numpy 的 Python 2.7,并且我被我的环境困住了。此外,数据已经过预处理,所以它被缩放并且所有值都是有效的 - 我不想在处理数据之前再次预处理数据以提取唯一类并构建字典。我真正要寻找的是 Python 中的 stringAsFactors 参数,它在脚本读取数据时自动将字符串向量转换为因子向量。

不要问我为什么使用 Python 而不是 R - 我会按照我说的去做。

谢谢,CC。

最佳答案

您可以使用 np.unique return_inverse=True 来返回唯一的类名和一组相应的整数索引:

import numpy as np

classes = np.array(['a', 'b', 'c', 'c', 'b', 'a', 'a', 'd'])

classnames, indices = np.unique(classes, return_inverse=True)

print(classnames)
# ['a' 'b' 'c' 'd']

print(indices)
# [0 1 2 2 1 0 0 3]

print(classnames[indices])
# ['a' 'b' 'c' 'c' 'b' 'a' 'a' 'd']

类名将按词法顺序排序。

关于Python:如何将字符串数组转换为因子列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34682420/

10-11 22:09
查看更多