将3d Numpy数组转换为2d [英] Convert 3d Numpy array to 2d

查看:155
本文介绍了将3d Numpy数组转换为2d的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下形式的3d numpy数组:

I have a 3d numpy array of following form:

array([[[ 1.,  5.,  4.],
    [ 1.,  5.,  4.],
    [ 1.,  2.,  4.]],

   [[ 3.,  6.,  4.],
    [ 6.,  6.,  4.],
    [ 6.,  6.,  4.]]])

是否有一种有效的方法可以将其转换为2d形式的数组:

Is there a efficient way to convert it to a 2d array of form:

array([[1, 1, 1, 5, 5, 2, 4, 4, 4],
   [3, 6, 6, 6, 6, 6, 4, 4, 4]])

非常感谢!

推荐答案

In [54]: arr = np.array([[[ 1.,  5.,  4.],
                         [ 1.,  5.,  4.],
                         [ 1.,  2.,  4.]],

                        [[ 3.,  6.,  4.],
                         [ 6.,  6.,  4.],
                         [ 6.,  6.,  4.]]])

In [61]: arr.reshape((arr.shape[0], -1), order='F')
Out[61]: 
array([[ 1.,  1.,  1.,  5.,  5.,  2.,  4.,  4.,  4.],
       [ 3.,  6.,  6.,  6.,  6.,  6.,  4.,  4.,  4.]])


数组arr的形状为(2, 3, 3).我们希望保留长度为2的第一个轴,并展平长度为3的两个轴.


The array arr has shape (2, 3, 3). We wish to keep the first axis of length 2, and flatten the two axes of length 3.

如果我们调用 arr.reshape(h, w) ,然后NumPy将尝试重塑arr的形状以塑造(h, w)的形状.如果我们调用arr.reshape(h, -1),则NumPy将用使整形有意义的任何整数替换-1-在这种情况下为arr.size/h.

If we call arr.reshape(h, w) then NumPy will attempt to reshape arr to shape (h, w). If we call arr.reshape(h, -1) then NumPy will replace the -1 with whatever integer is needed for the reshape to make sense -- in this case, arr.size/h.

因此

In [63]: arr.reshape((arr.shape[0], -1))
Out[63]: 
array([[ 1.,  5.,  4.,  1.,  5.,  4.,  1.,  2.,  4.],
       [ 3.,  6.,  4.,  6.,  6.,  4.,  6.,  6.,  4.]])

这几乎是我们想要的,但是请注意每个子数组中的值,例如

This is almost what we want, but notice that the values in each subarray, such as

[[ 1.,  5.,  4.],
[ 1.,  5.,  4.],
[ 1.,  2.,  4.]]

在向下一行之前,通过从左向右行进来遍历

. 我们想在继续下一行之前进入下一行. 为此,请使用order='F'.

are being traversed by marching from left to right before going down to the next row. We want to march down the rows before going on to the next column. To achieve that, use order='F'.

通常在C-order中访问NumPy数组中的元素-最后一个索引移动最快.如果我们访问F-order中的元素,则第一个索引的移动速度最快.由于在形状为(h, w)的2D数组中,第一个轴与行相关联,最后一个轴与列相关联,因此在F-order中遍历该数组会沿每一行向下移动,然后再移至下一列.

Usually the elements in a NumPy array are visited in C-order -- where the last index moves fastest. If we visit the elements in F-order then the first index moves fastest. Since in a 2D array of shape (h, w), the first axis is associated with the rows and the last axis the columns, traversing the array in F-order marches down each row before moving on to the next column.

这篇关于将3d Numpy数组转换为2d的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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