【问题标题】:What is the most pythonic way to split a 3d array to 2d arrays with different second indexes?将 3d 数组拆分为具有不同第二个索引的 2d 数组的最 Pythonic 方法是什么?
【发布时间】:2017-11-17 16:44:38
【问题描述】:

我有一个函数 foo,它返回一个形状为 (1000, 3, 1000) 的数组 如何将其拆分为三个数组 a(1000, 1000) 和 b(1000, 1000) 和 c(1000, 1000) 我正在寻找这样的东西:

a,b,c = foo()[:,*,:]

这将导致 a,b,c 等于:

res = foo()
a = res[:,0,:]
b = res[:,1,:]
c = res[:,2,:]

【问题讨论】:

  • 你的问题不清楚,请展示你的尝试

标签: python arrays multidimensional-array


【解决方案1】:

我相信以下任何一种方法都会起作用:

numpy.split(foo(), 3, axis=1)
numpy.hsplit(foo(),3)
list(numpy.swapaxes(foo(), 0, 1))

【讨论】:

    【解决方案2】:

    这也应该有效:

    a,b,c = np.rollaxis(foo(), 1)
    

    【讨论】:

      【解决方案3】:

      类似于你的previous question:

      def foo():
          return np.ones((1000, 3, 1000))
      
      a, b, c = [np.squeeze(arr) for arr in np.hsplit(foo(), foo().shape[1])]
      
      for arr in [a, b, c]:
          print(arr.shape)
      # (1000, 1000)
      # (1000, 1000)
      # (1000, 1000)
      

      没有np.squeeze,你会得到 (1000, 1, 1000) 的形状。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-13
        相关资源
        最近更新 更多