利用numpy的newaxis轉變矩陣的形狀

title: hange shape of matrix by numpy
tags: python, numpy


簡單筆記一下:
有一個一維陣列x1,我分別想要把它變成一個3*1的矩陣x2,以及1*3的矩陣x3,作法如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import numpy as np
x1 = np.array([10, 20, 30], float)
print "shape of x1 is ", x1.shape
print x1

x2 = x1[:, np.newaxis]
print "shape of x2 is ", x2.shape
print x2

x3 = x1[np.newaxis, :]
print "shape of x3 is ", x2.shape
print x2

---result---
shape of x1 is (3,)
[ 10. 20. 30.]
shape of x2 is (3, 1)
[[ 10.]
[ 20.]
[ 30.]]
shape of x3 is (3, 1)
[[ 10.]
[ 20.]
[ 30.]]