我有一个大小为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
1条答案
按热度按时间oug3syen1#
因为你有值0,1,2,我会使用一个引用数组通过索引来Map这些值:
输出: