在列块中展平或分组数组-NumPy/Python [英] Flatten or group array in blocks of columns - NumPy / Python

查看:132
本文介绍了在列块中展平或分组数组-NumPy/Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么简单的方法可以压平

Is there any easy way to flatten

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

进入

array([ 0,  1,  4,  5, 8, 9, 2, 3, 6, 7, 10, 11])

推荐答案

似乎您正在考虑考虑使用特定数量的cols来形成块,然后获取每个块中的元素,然后移至下一个.因此,考虑到这一点,这是一种方法-

It seems like you are looking to consider a specific number of cols to form blocks and then getting the elements in each block and then moving onto the next ones. So, with that in mind, here's one way -

In [148]: a
Out[148]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [149]: ncols = 2 # no. of cols to be considered for each block

In [150]: a.reshape(a.shape[0],-1,ncols).swapaxes(0,1).ravel()
Out[150]: array([ 0,  1,  4,  5,  8,  9,  2,  3,  6,  7, 10, 11])

this post 中详细讨论了背后的动机.

The motivation behind is discussed in detail in this post.

另外,要保留2D格式-

Additionally, to keep the 2D format -

In [27]: a.reshape(a.shape[0],-1,ncols).swapaxes(0,1).reshape(-1,ncols)
Out[27]: 
array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [ 2,  3],
       [ 6,  7],
       [10, 11]])

并采用直观 3D数组格式-

And to have it in a intuitive 3D array format -

In [28]: a.reshape(a.shape[0],-1,ncols).swapaxes(0,1)
Out[28]: 
array([[[ 0,  1],
        [ 4,  5],
        [ 8,  9]],

       [[ 2,  3],
        [ 6,  7],
        [10, 11]]])

这篇关于在列块中展平或分组数组-NumPy/Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆