numpy建立矩陣經常使用方法

numpy建立矩陣經常使用方法

arange+reshape

in:

n = np.arange(0, 30, 2)# start at 0 count up by 2, stop before 30 n = n.reshape(3, 5) # reshape array to be 3x5
  • 1
  • 2

out:

這裏寫圖片描述

linspace+resize

in:

o = np.linspace(0, 4, 9) o.resize(3, 3)
  • 1
  • 2

out:

這裏寫圖片描述

notice:reshape與resize區別

ones zeros eye diag random.randint等建立矩陣

in:

np.ones((3, 2)) np.zeros((2, 3)) np.eye(3)#3維單位矩陣 y = np.array([4, 5, 6]) np.diag(y)#以y爲主對角線建立矩陣 np.random.randint(0, 10, (4,3))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

out:

ones: 
[[ 1. 1.] 
[ 1. 1.] 
[ 1. 1.]] 
zeros: 
[[ 0. 0. 0.] 
[ 0. 0. 0.]] 
eye: 
[[ 1. 0. 0.] 
[ 0. 1. 0.] 
[ 0. 0. 1.]] 
diag: 
[[4 0 0] 
[0 5 0] 
[0 0 6]] 
randint 
[[1 3 5] 
[4 4 3] 
[9 3 0] 
[7 0 0]]python

矩陣拼接

in:

p = np.ones([2, 3], int) np.hstack([p, 2*p])#水平拼接 np.vstack([p, 2*p])#豎直拼接
  • 1
  • 2
  • 3

out:

hstack: 
[[1 1 1 2 2 2] 
[1 1 1 2 2 2]] 
vstack: 
[[1 1 1] 
[1 1 1] 
[2 2 2] 
[2 2 2]]dom

備註:ui

1 矩陣經常使用操做:spa

>>> b1 = array([[1,2,3],[4,5,6],[7,8,9]])
>>> b1[1:2]
array([[4, 5, 6]]).net

相關文章
相關標籤/搜索