简体   繁体   English

如何在numpy中通过子数组优雅地重新排列数组?

[英]How to rearrange an array by subarray elegantly in numpy?

Let's say I have a 3-D array: 假设我有一个3-D数组:

[[[0,1,2],
  [0,1,2],
  [0,1,2]],

 [[3,4,5],
  [3,4,5],
  [3,4,5]]]

And I want to rearrange this by the columns: 我想按列重新排列:

[[0,1,2,3,4,5],
 [0,1,2,3,4,5],
 [0,1,2,3,4,5]]

What would be an elegant python numpy code for doing this for essentially a 3-D np.array of arbitrary shape and depth? 对于本质上具有任意形状和深度的3-D np.array进行此操作,将是什么优雅的python numpy代码? Could there be a fast method that bypasses for loop? 有没有一种快速的方法可以绕过循环? All the approaches I made were terribly adhoc and brute they were basically too slow and useless... 我所采取的所有方法都是非常彻底和粗暴的,它们基本上太慢且无用。

Thanks!! 谢谢!!

Swap axes and reshape - 交换轴并重塑-

a.swapaxes(0,1).reshape(a.shape[1],-1)

Sample run - 样品运行-

In [115]: a
Out[115]: 
array([[[0, 1, 2],
        [0, 1, 2],
        [0, 1, 2]],

       [[3, 4, 5],
        [3, 4, 5],
        [3, 4, 5]]])

In [116]: a.swapaxes(0,1).reshape(a.shape[1],-1)
Out[116]: 
array([[0, 1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4, 5]])

Using einops: 使用einops:

einops.rearrange(a, 'x y z -> y (x z) ')

And I would recommend to give meaningful names to axes (instead of xyz) depending on the context (eg time, height, etc.). 并且我建议根据上下文(例如时间,高度等)为轴指定有意义的名称(而不是xyz)。 This will make it easy to understand what the code does 这将使您易于理解代码的作用

In : einops.rearrange(a, 'x y z -> y (x z) ')
Out:
array([[0, 1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4, 5]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM