在numpy中创建一个方形矩阵的3D数组

时间:2014-09-16 10:34:37

标签: python numpy multidimensional-array

我想要矢量化一组2x2数组的创建, 所以我写了以下代码

import numpy as np
# an array of parameters
a = np.array(( 1.0, 10.0, 100.0))
# create a set of 2x2 matrices
b = np.array((( 1*a, 2*a), ( 3*a, 4*a)))

# to access the 2x2 matrix, I can do as follows
for i in range(3):
    print(i,"\n",b[:,:,i])

,其输出为

0 
 [[ 1.  2.]
 [ 3.  4.]]
1 
 [[ 10.  20.]
 [ 30.  40.]]
2 
 [[ 100.  200.]
 [ 300.  400.]]

到目前为止,这么好,但我真正喜欢的是在某些不同的地方创建b 方式,以便我可以简单地通过

引用2x2矩阵
b = ...
# this code doesn't work!
for i in range(3):
    print(i,"\n",b[i])
提前谢谢,

2 个答案:

答案 0 :(得分:1)

numpy.transpose;为你的例子:

>>> b.transpose(2, 0, 1)
array([[[   1.,    2.],
        [   3.,    4.]],

       [[  10.,   20.],
        [  30.,   40.]],

       [[ 100.,  200.],
        [ 300.,  400.]]])
>>> b.transpose(2, 0, 1)[0]
array([[ 1.,  2.],
       [ 3.,  4.]])

答案 1 :(得分:0)

这是一个选项:

>>> b = np.array([1,2,3,4]).reshape((2,2)) * np.ones((3,2,2)) * np.array([1,10,100])[...,None,None]

>>> for i in range(3):
...     print i,"\n",b[i]
0 
[[ 1.  2.]
 [ 3.  4.]]
1 
[[ 10.  20.]
 [ 30.  40.]]
2 
[[ 100.  200.]
 [ 300.  400.]]