【问题标题】:How to shift a 2D numpy array in python?如何在 python 中移动 2D numpy 数组?
【发布时间】:2019-06-21 09:17:26
【问题描述】:

如何在 Python 中移动 2D numpy 数组的元素?

例如转换这个数组:

[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]]

到这个数组:

[[0, 0, 0,],
[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]]

【问题讨论】:

    标签: python arrays numpy 2d shift


    【解决方案1】:
    import numpy as np
    a = np.array([[ 1, 2, 3],
                  [ 4, 5, 6],
                  [ 7, 8, 9],
                  [10, 11, 12]])    
    
    def shift_array(array, place):
        new_arr = np.roll(array, place, axis=0)
        new_arr[:place] = np.zeros((new_arr[:place].shape))
        return new_arr
    
    shift_array(a,2)
    
    # array([[ 0,  0,  0],
    #        [ 0,  0,  0],
    #        [ 1,  2,  3],
    #        [ 4,  5, 6]])
    

    【讨论】:

      【解决方案2】:

      我想手动进行,切片是这样工作的:

      import numpy as np
      
      A = np.array([[ 1, 2, 3],
                    [ 4, 5, 6],
                    [ 7, 8, 9],
                    [10, 11, 12]])
      
      A[1:,:] = A[:3,:]
      A[:1,:] = [0, 0, 0]
      

      【讨论】:

        猜你喜欢
        • 2021-02-19
        • 2021-10-12
        • 2020-11-05
        • 2015-08-13
        • 2012-06-08
        • 1970-01-01
        • 2016-06-10
        • 2017-11-22
        • 1970-01-01
        相关资源
        最近更新 更多