【问题标题】:Python: how to convert a string array to a factor listPython:如何将字符串数组转换为因子列表
【发布时间】:2016-04-13 10:52:30
【问题描述】:

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

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

谢谢,抄送。

【问题讨论】:

    标签: python arrays numpy set-operations


    【解决方案1】:

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

    类名将按词法排序。

    【讨论】:

    • 谢谢。我觉得这必须很容易,但我找到的所有答案都需要创建一个字典。最后一点(问题中没有问到)是:“indices.astype('S10')”,它将整数值转换为实际类别,这是我在分类例程中需要的。您的答案完美无缺。再次感谢您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2011-03-18
    • 2011-05-16
    相关资源
    最近更新 更多