【问题标题】:Repeat last column in numpy array重复numpy数组中的最后一列
【发布时间】:2018-07-26 01:26:08
【问题描述】:

问题

我正在尝试重复 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]]

我是如何解决这个问题的

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]

其他方式

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

【问题讨论】:

    标签: python arrays performance numpy optimization


    【解决方案1】:

    广播通常很有效。

    import numpy as np
    
    A = np.random.randint(0, 100, (1000, 1000))
    
    np.hstack((A, np.broadcast_to(A[:, -1][:, None], (A.shape[1], n))))
    

    如果性能是一个问题,一些基准测试:

    n = 1000
    %timeit np.hstack((A, np.broadcast_to(A[:, -1][:, None], (A.shape[1], n))))  # 3.06 ms
    %timeit np.hstack((A, np.tile(A[:, [-1]], n)))                               # 9.33 ms
    %timeit np.repeat(A, [1]*(A.shape[1]-1) +[n], axis=1)                        # 12.9 ms
    

    【讨论】:

      【解决方案2】:

      使用numpy.repeat():

      np.repeat(a, [1]*(a.shape[1]-1) +[3], axis=1)
      

      【讨论】:

        【解决方案3】:

        一种可能的解决方案:

        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]]
        

        【讨论】:

          猜你喜欢
          • 2019-04-15
          • 2021-09-24
          • 2018-11-25
          • 1970-01-01
          • 1970-01-01
          • 2015-03-27
          • 2018-03-30
          • 2019-12-07
          • 1970-01-01
          相关资源
          最近更新 更多