4

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

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

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

使用 numpy,我将所有数值列读入矩阵,最后一列读入我称之为“类”的数组。事实上,我事先并不知道类名,所以我不想使用字典。我也不想使用熊猫。这是问题的一个例子:

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

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

谢谢,CC。

4

1 回答 1

11

您可以使用np.uniquewithreturn_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']

类名将按词汇顺序排序。

于 2016-01-08T17:14:57.170 回答