如何用多个值替换numpy数组中的每个元素?

wwodge7n  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(123)

我有一个大小为n * m的2D numpy数组,我需要用2个值替换每个值,得到一个大小为n * 2m的数组。
替换图案:1[1,0]2[0,1]以及0[0,0]
输入:[[1,0,2],[2,2,1]]
预期输出:[[1,0,0,0,0,1],[0,1,0,1,1,0]]
这可以很容易地用一个for循环来完成,但是我试图找到一种“麻木”的方式来实现它,以达到最大的效率。

res = np.zeros((arr.shape[0],arr.shape[1]*2))
for index, row in enumerate(arr):
    temp = np.array([])
    for e in row:
        if e == 1:
            temp = np.append(temp,[1,0])
        elif e == 2:
            temp = np.append(temp,[0,1])
        else:
            temp = np.append(temp,[0,0])
    res[index] = temp
oug3syen

oug3syen1#

因为你有值0,1,2,我会使用一个引用数组通过索引来Map这些值:

a = np.array([[1,0,2],[2,2,1]])
mapper = np.array([[0, 0],  # position 0
                   [1, 0],  # position 1
                   [0, 1]]) # position 2

out = mapper[a].reshape((len(a), -1))

输出:

array([[1, 0, 0, 0, 0, 1],
       [0, 1, 0, 1, 1, 0]])

相关问题