重塑numpy的数组 [英] Reshape an array in NumPy

查看:149
本文介绍了重塑numpy的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下形式的阵列(只是一个例子):

  [0 1]
 [2〜3]
 [4]
 [6 7]
 [8 9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]

它的形状为[9,2]。现在我想变换数组,这样每一列变成形状[3,3],如:

  [0 6月12日]
 [2 8 14]
 [4 10 16]
[[1 7 13]
 [3 9 15]
 [5月11日17]

最明显的(且确实的非Python化)的解决方案是初始化为零的阵列以适当的尺寸和运行两个for循环在那里将被填充数据。我感兴趣的是一个解决方案,是语言顺应...


解决方案

  A = np.arange(18).reshape(9,2)
B = a.reshape(3,3,2).swapaxes(0,2)# 一个:
阵列([0,1],
       [2,3]
       [4,5],
       [6,7]
       [8,9]
       [10,11],
       [12,13],
       [14,15],
       [16,17]])
#乙:
阵列([[[0,6,12]
        [2,8,14],
        [4,10,16]]       [[1,7,13],
        [3,9,15],
        [5,11,17]]])

Consider an array of the following form (just an example):

[[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

It's shape is [9,2]. Now I want to transform the array so that each column becomes a shape [3,3], like this:

[[ 0  6 12]
 [ 2  8 14]
 [ 4 10 16]]
[[ 1  7 13]
 [ 3  9 15]
 [ 5 11 17]]

The most obvious (and surely "non-pythonic") solution is to initialise an array of zeroes with the proper dimension and run two for-loops where it will be filled with data. I'm interested in a solution that is language-conform...

解决方案

a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])


# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

这篇关于重塑numpy的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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