【问题标题】:Reshaping Python array in a particular way以特定方式重塑 Python 数组
【发布时间】:2018-06-20 19:21:25
【问题描述】:

我正在编写 Python 代码,因此我基本上可以使用 Numpy 数组来完成此操作

我有一个 Matlab 代码,它是

A = [1:30]'; % Example matrix
rows = 3;

for i=1:(numel(A)-rows+1)
    B(1:rows,i)=A(i:i+rows-1,1);
end

或者,没有任何循环,

B = conv2(A.', flip(eye(rows)));

B = B(:, rows:end-rows+1);

有人可以帮我在 Python 中做同样的事情吗?使用 reshape 函数没有帮助,因为我需要“镜像”这些值(而不仅仅是重新组织它们)。

谢谢。

【问题讨论】:

  • 这是一个 NumPy 数组吗?
  • @miradulo 是的,它是一个 NumPy 数组 miradulo

标签: python arrays numpy matrix reshape


【解决方案1】:

不是很性感,但不适合

import numpy as np

a = np.arange(1,31)
b = np.arange(3).reshape(3,1)
c = b+a[:28]

正在尝试翻译您的 matlab 代码

import numpy as np
from scipy.signal import convolve2d

a = np.arange(1,31).reshape(1,30)
b = np.flip(np.eye(3,28),0)
c = convolve2d(a, b)[:,2:28]

【讨论】:

    【解决方案2】:

    使用np.ndarray.reshape

    import numpy as np
    
    A = np.arange(1, 31)
    B = A.reshape((3, 10))
    
    print(B)
    
    [[ 1  2  3  4  5  6  7  8  9 10]
     [11 12 13 14 15 16 17 18 19 20]
     [21 22 23 24 25 26 27 28 29 30]]
    

    【讨论】:

      【解决方案3】:

      这是给你的代码。

      import numpy as np
      
      A = np.array(list(range(1,31)))
      
      rows = 3
      
      new_A = np.zeros((rows,A.size-rows+1))
      
      for i in range(rows):
          new_A[i,:] = A[i:A.size-rows+i+1]
      
      print (new_A)    
      

      【讨论】:

        【解决方案4】:

        试试那个代码 sn-p:

        import numpy as np
        start = 1
        end = 30
        b_dim = 28
        
        a = np.arange(start, end+1)
        b = np.zeros((3, b_dim))
        
        print("a = ", a)
        
        rows, _ = b.shape
        
        for row in range(rows):
            data = a[row:row+b_dim]
            b[row, :] = data
        
        print("b = ", b)
        

        打印出来

        ('a = ', array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
               18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]))
        ('b = ', array([[  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,
                 12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,
                 23.,  24.,  25.,  26.,  27.,  28.],
               [  2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,  12.,
                 13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,  23.,
                 24.,  25.,  26.,  27.,  28.,  29.],
               [  3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,  12.,  13.,
                 14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,  23.,  24.,
                 25.,  26.,  27.,  28.,  29.,  30.]]))
        

        【讨论】:

        • 那是我的马虎 8 =)
        • 嘿,别担心!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-11
        相关资源
        最近更新 更多