python - 在列块中展平或分组数组 - NumPy / Python
问题描述
有什么简单的方法可以压扁
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 来形成块,然后获取每个块中的元素,然后移动到下一个块中。因此,考虑到这一点,这是一种方法 -
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
。
此外,为了保持 2D 格式 -
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 数组格式显示它 -
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]]])
推荐阅读
- javascript - EJS - 在样式标签属性中写入 js 变量
- flutter - Flutter 日历取消操作
- ms-word - 是否可以在 Word 365 中编辑后台?
- wordpress - Wordpress - 自定义模板分页未显示(Lollum 框架 - 莲花主题)
- automation - 如何将文件从我的 Android 设备拉到我 PC 上的本地文件夹
- django - Django迁移无法将用户实例分配给用户字段
- r - read_html(url) 和 read_html(content(GET(url), "text")) 之间的区别
- javascript - EventListener 不会在函数调用时被删除
- mysql - 通过在特定表上添加 JOIN 非常慢的 SQL 查询
- python - 如何从 Browsermob-proxy 获取标头?