简体   繁体   English

左移 2D Numpy 数组的每一行独立

[英]Left shift each row of 2D Numpy array independently

A = np.array([[4.0, 3, 2],
              [1, 2, 3],
              [0, -1, 5]])

shift = np.array([1,2,1])

out = np.array([[3, 2, np.nan],
              [3, np.nan, np.nan],
              [-1, 5, np.nan]])

I want to left shift the 2D numpy array towards the left for each row independently as given by the shift vector and impute the right with Nan.我想将 2D numpy 数组向左移动,每一行独立地由移位向量给出,并用 Nan 归因于右侧。

Please help me out with this这个你能帮我吗

Thanks谢谢

import numpy as np

A = np.array([[4, 3, 2],
              [1, 2, 3],
              [0, -1, 5]])

shift = np.array([1,2,1])


x,y = A.shape
res = np.full(x*y,np.nan).reshape(x,y)

for i in range(x):
    for j in range(y):
        res[i][:(y-shift[i])]=A[i][shift[i]:]
print(res)

Using Roll rows of matrix Ref使用矩阵Ref的 Roll 行

from skimage.util.shape import view_as_windows as viewW
import numpy as np


A = np.array([[4, 3, 2],
              [1, 2, 3],
              [0, -1, 5]])

shift = np.array([1,1,1])

p = np.full((A.shape[0],A.shape[1]-1),np.nan)
a_ext = np.concatenate((A,p,p),axis=1)


n = A.shape[1]
shifted =viewW(a_ext,(1,n))[np.arange(len(shift)), -shift + (n-1),0]


print(shifted)

output # output#

[[ 3.  2. nan]
 [ 2.  3. nan]
 [-1.  5. nan]]

you should just use a for loop and np.roll per row.你应该只使用一个 for 循环和np.roll每行。

import numpy as np
A = np.array([[4, 3, 2],
              [1, 2, 3],
              [0, -1, 5]]).astype(float)

shift = np.array([1,2,1])

out = np.copy(A)
for i,shift_value in enumerate(shift):
    out[i,:shift_value] = np.nan
    out[i,:] = np.roll(out[i,:], -shift_value, 0)
print(out)
[[ 3.  2. nan]
 [ 3. nan nan]
 [-1.  5. nan]]

while someone might think that reducing the calls to np.roll will help, it won't because this is exactly the way np.roll is implemented internally, and you'll have 2 loops in your code instead of 1.虽然有人可能认为减少对np.roll的调用会有所帮助,但事实并非如此,因为这正是np.roll内部实现的方式,并且您的代码中将有 2 个循环而不是 1 个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM