重复numpy数组中的最后一列

clf*_*ter 7 python arrays optimization performance numpy

问题

我正在尝试重复 Numpy 数组中的最后一列。有没有比调整数组大小、复制值和重复最后一行 x 次更“优雅”的方法?

我想要达到的目标

Input Array:                        Output Array:
[[1,2,3],                           [[1,2,3,3,3],
 [0,0,0],    -> repeat(2-times) ->   [0,0,0,0,0],
 [0,2,1]]                            [0,2,1,1,1]]
Run Code Online (Sandbox Code Playgroud)

我是如何解决问题的

x = np.array([[1,2,3],[0,0,0],[0,2,1]])
# to repeat last row two times two times
new_size = x.shape[1] + 2
new_x = np.zeros((3,new_size))
new_x[:,:3] = x

for i in range(x.shape[1],new_size):
    new_x[:,i] = x[:,-1]
Run Code Online (Sandbox Code Playgroud)

另一种方式

有没有办法用 numpy repeat 函数解决这个问题?或者更短或更有效的东西?

jez*_*ael 6

一种可能的解决方案:

a = np.hstack((arr, np.tile(arr[:, [-1]], 2)))
print (a)
[[1 2 3 3 3]
 [0 0 0 0 0]
 [0 2 1 1 1]]
Run Code Online (Sandbox Code Playgroud)