简体   繁体   English

将3d Numpy数组转换为2d

[英]Convert 3d Numpy array to 2d

I have a 3d numpy array of following form: 我有一个3d numpy数组的以下形式:

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

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

Is there a efficient way to convert it to a 2d array of form: 有没有一种有效的方法将其转换为2d数组的形式:

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

Thanks a lot! 非常感谢!

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.]])

The array arr has shape (2, 3, 3) . 阵列arr具有形状(2, 3, 3) arr (2, 3, 3) We wish to keep the first axis of length 2, and flatten the two axes of length 3. 我们希望保持第一个长度为2的轴,并使两个长度为3的轴变平。

If we call arr.reshape(h, w) then NumPy will attempt to reshape arr to shape (h, w) . 如果我们调用arr.reshape(h, w)那么NumPy将尝试重塑arr以形成(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 . 如果我们调用arr.reshape(h, -1)那么NumPy会将-1替换为重塑arr.size/h所需的任何整数 - 在本例中为arr.size/h

Hence, 因此,

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.]]

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' . 为此,请使用order='F'

Usually the elements in a NumPy array are visited in C-order -- where the last index moves fastest. 通常,NumPy数组中的元素以C-order访问 - 其中最后一个索引移动得最快。 If we visit the elements in F-order then the first index moves fastest. 如果我们以F-order访问元素,那么第一个索引移动得最快。 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. 由于在形状(h, w)的2D数组中,第一个轴与行相关联,最后一个轴与列相关联,以F-order遍历数组,然后向前移动到下一列。

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

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