python - 将 numpy 数组中的整数转换为连续范围 0...n

标签 python arrays numpy

我想将 numpy 数组中的任意整数转换为连续范围 0...n,如下所示:

source: [2 3 4 5 4 3]
translating [2 3 4 5] -> [0 1 2 3]
target: [0 1 2 3 2 1]

必须有比以下更好的方法:

import numpy as np

"translate arbitrary integers in the source array to contiguous range 0...n"

def translate_ids(source, source_ids, target_ids):
    target = source.copy()

    for i in range(len(source_ids)):
        x = source_ids[i]
        x_i = source == x
        target[x_i] = target_ids[i]

    return target

#

source = np.array([ 2, 3, 4, 5, 4, 3 ])
source_ids = np.unique(source)
target_ids = np.arange(len(source_ids))

target = translate_ids(source, source_ids, target_ids)

print "source:", source
print "translating", source_ids, '->', target_ids
print "target:", target

这是什么?

最佳答案

IIUC 你可以简单地使用 np.unique的可选参数 return_inverse,像这样 -

np.unique(source,return_inverse=True)[1]

sample 运行-

In [44]: source
Out[44]: array([2, 3, 4, 5, 4, 3])

In [45]: np.unique(source,return_inverse=True)[1]
Out[45]: array([0, 1, 2, 3, 2, 1])

关于python - 将 numpy 数组中的整数转换为连续范围 0...n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38513646/

相关文章:

python - 如何在 Django 应用程序中转换时区

c++ - 将整数转换为字符数组函数

java - 帮助尝试理解圆形阵列中的模运算

JavaScript 语法问题 : [{ }] hierarchy

python - 在 matplotlib 中为 NaN 值设置颜色

python-3.x - 如何通过比较两列对数据框进行排序

python - urllib/urllib2 返回的错误码和实际页面

python - 计算坐标对之间的最小距离

python - NameError:名称 'self' 未在 EXEC/EVAL 中定义

python - 为 numpy 数组分配 2D 数组函数返回值