【问题标题】:Translate integers in a numpy array to a contiguous range 0...n将 numpy 数组中的整数转换为连续范围 0...n
【发布时间】:2020-01-10 05:33:08
【问题描述】:

我想将 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

这是什么?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    pandas.factorize 是一种方法:

    import pandas as pd
    
    lst = [2, 3, 4, 5, 4, 3]
    res = pd.factorize(lst, sort=True)[0]
    
    # [0 1 2 3 2 1]
    

    注意:这会返回一个列表,而np.unique 将始终返回一个np.ndarray

    【讨论】:

      【解决方案2】:

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

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

      示例运行 -

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

      【讨论】:

      • 很高兴指出这是否保留了 order 的属性。例如:零值是否保持其值?
      • @RadioControlled 它将 min 到 max 映射到 0..n seq。因此,如果 0 是最小元素,则它保持为 0。
      • 其他元素呢?他们遵守秩序吗? np.argsort(source)==np.argsort(np.unique(source,return_inverse=True)[1]) 代表所有 source?
      • @RadioControlled 是的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      相关资源
      最近更新 更多