假设我有一个填充了随机整数的矩阵'R'
import numpy as np
matR = np.random.randint(-10,10,size=(4,6))
>>> matR = [[-4 -4 1 -8 -2 5]
[ 9 2 -4 -1 4 2]
[ 7 8 -2 -9 3 8]
[ 9 -3 3 6 4 3]]
现在我知道我可以像这样抽样:
>>> matR[::2,::2] = [[-4 1 -2]
[ 7 -2 3]]
然而,我真正想要的是干净利落的方式:
>>> matR.?? = [[-4 0 1 0 -2 0]
[ 0 0 0 0 0 0]
[ 7 0 -2 0 3 0]
[ 0 0 0 0 0 0]]
我想避免python循环,使用枚举很容易。
答案 0 :(得分:3)
你想要这样的东西吗?
>>> import numpy as np
>>> m = np.random.randint(-10,10,size=(4,6))
>>> m
array([[ 7, 4, 7, 7, 5, 9],
[ 5, -7, -2, 4, 2, -4],
[ -9, 4, 6, 8, 5, -10],
[ -6, -8, 8, -5, 2, -3]])
>>> m2 = np.zeros_like(m) # or m2 = m*0
>>> m2[::2, ::2] = m[::2, ::2]
>>> m2
array([[ 7, 0, 7, 0, 5, 0],
[ 0, 0, 0, 0, 0, 0],
[-9, 0, 6, 0, 5, 0],
[ 0, 0, 0, 0, 0, 0]])
答案 1 :(得分:1)
如何保持面具?
>>> import numpy as np
>>> shape = (4,6)
>>> m = np.random.randint(-10,10,size = shape)
>>> mask = np.zeros(shape,dtype = np.int32)
>>> mask[::2,::2] = 1
>>> mask
array([[1, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0]])
>>> m
array([[-7, 0, -4, -8, 0, 0],
[ 0, -3, -2, -1, 1, 2],
[ 8, -8, 5, 1, 9, 1],
[ 1, 0, 2, 7, 4, -8]])
>>> m * mask
array([[-7, 0, -4, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0],
[ 8, 0, 5, 0, 9, 0],
[ 0, 0, 0, 0, 0, 0]])