抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

有一個一維陣列 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
import numpy as np

x1 = np.array([10, 20, 30], float)

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

print("shape of x1 is ", x1.shape)
print(x1)

print("-------------")

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

print("-------------")

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

output:

1
2
3
4
5
6
7
8
9
10
shape of x1 is  (3,)
[ 10. 20. 30.]
-------------
shape of x2 is (3, 1)
[[ 10.]
[ 20.]
[ 30.]]
-------------
shape of x3 is (1, 3)
[[ 10. 20. 30.]]

Reference

Comments