A B*_*A B 13 python arrays numpy
我有一个数组x
:
x = [0, -1, 0, 3]
Run Code Online (Sandbox Code Playgroud)
我想要y
:
y = [[0, -2, 0, 2],
[0, -1, 0, 3],
[0, 0, 0, 4]]
Run Code Online (Sandbox Code Playgroud)
第一行是x-1
第二行x
,第三行是第三行x+1
.所有偶数列索引都为零.
我正在做:
y=np.vstack(x-1, x, x+1)
y[0][::2] = 0
y[1][::2] = 0
y[2][::2] = 0
Run Code Online (Sandbox Code Playgroud)
我以为可能会有一个单行代替4而不是4.
Mik*_*ler 10
>>> x = np.array([0, -1, 0, 3])
>>> y = np.vstack((x-1, x, x+1))
>>> y[:,::2] = 0
>>> y
array([[ 0, -2, 0, 2],
[ 0, -1, 0, 3],
[ 0, 0, 0, 4]])
Run Code Online (Sandbox Code Playgroud)
y[:, ::2]
Run Code Online (Sandbox Code Playgroud)
给出了完整的第一维度.即所有行和每个其他条目形成第二个维度,即列:
array([[-1, -1],
[ 0, 0],
[ 1, 1]])
Run Code Online (Sandbox Code Playgroud)
这不同于:
y[:][::2]
Run Code Online (Sandbox Code Playgroud)
因为这分两步完成.第一步:
y[:]
Run Code Online (Sandbox Code Playgroud)
给出了整个数组的视图:
array([[-1, -2, -1, 2],
[ 0, -1, 0, 3],
[ 1, 0, 1, 4]])
Run Code Online (Sandbox Code Playgroud)
因此,第二步基本上是这样做的:
y[::2]
array([[-1, -2, -1, 2],
[ 1, 0, 1, 4]])
Run Code Online (Sandbox Code Playgroud)
它沿着第一个维度工作.即行.