numpy 數(shù)組常用函數(shù)
where
import numpy as np
a = np.arange(1,10)
print(a,"\n")
b = np.arange(1,10).reshape((3,3))
print(b,"\n")
[1 2 3 4 5 6 7 8 9]
[[1 2 3]
[4 5 6]
[7 8 9]]
#np.where(condition,[x,y])
np.where(a>5)
#索引為5.6.7.8的4個(gè)位置的數(shù)大于5
(array([5, 6, 7, 8], dtype=int64),)
a[np.where(a>5)]
#打印出滿足條件的a的值而不是索引位置
array([6, 7, 8, 9])
np.where(b>5)
#b中的6,7,8,9 4個(gè)數(shù)大于5,索引位置為(1,2)(第二行第三列)训枢,(2,0)(第三行第一列)撑螺,(2,1)(第三行第二列)店量,(2,2)第三行第二列)
(array([1, 2, 2, 2], dtype=int64), array([2, 0, 1, 2], dtype=int64))
np.where(b>5,b,0)
#有x普气,y時(shí)捐友,condition為True時(shí)取x中的值甫恩,否則取y中的值
array([[0, 0, 0],
[0, 0, 6],
[7, 8, 9]])
diag
print(b,"\n")
[[1 2 3]
[4 5 6]
[7 8 9]]
#取數(shù)組對(duì)角線的值
b1 = np.diag(b)
b2 = np.diag(b,1)
b3 = np.diag(b,-1)
print("b1: ",b1,"\n","b2: ",b2,"\n","b3: ",b3,"\n")
b1: [1 5 9]
b2: [2 6]
b3: [4 8]
take
np.take([1,2,3,4,5],[0,2,4])
array([1, 3, 5])
np.take([1,2,3,4,5],[[0,2],[1,4]])
array([[1, 3],
[2, 5]])
choose
a = np.arange(9).reshape((3,3))
print(a)
condition = [[1,1,1],[0,0,0],[2,2,2]]
[[0 1 2]
[3 4 5]
[6 7 8]]
np.choose(condition,a)
array([[3, 4, 5],
[0, 1, 2],
[6, 7, 8]])
np.choose(condition,a)擎颖,結(jié)果中的第一個(gè)元素,condition中的第一個(gè)1蔓钟,指a中的第2個(gè)元素組[3 4 5],第一個(gè)1的位置為0永票,所以對(duì)應(yīng)的元素為[3 4 5]的第一個(gè)元素3.以此類推,condition中的第2個(gè)1滥沫,指a中的第2個(gè)元素組[3 4 5],加上所在的位置侣集,所以對(duì)應(yīng)的元素為4...
np.choose(condition,[3,4,5])
array([[4, 4, 4],
[3, 3, 3],
[5, 5, 5]])
b = np.arange(9,18).reshape((3,3))
print(b)
[[ 9 10 11]
[12 13 14]
[15 16 17]]
np.choose(condition,[a,666,b])
array([[666, 666, 666],
[ 3, 4, 5],
[ 15, 16, 17]])
np.choose(b>14,(b,14))
array([[ 9, 10, 11],
[12, 13, 14],
[14, 14, 14]])
TRue =1 ,False=0
b>14
array([[False, False, False],
[False, False, False],
[ True, True, True]])
即[[0,0,0],[0,0,0],[1,1,1]] (b,14)
所以有 [[b,b,b],[b,b,b],[14,14,14]] 取b中對(duì)應(yīng)的位置的元素,=》
[[ 9, 10, 11],
[12, 13, 14],
[14, 14, 14]]
標(biāo)量運(yùn)算
a = np.arange(3)
print(a,"\n")
print(a +2)
[0 1 2]
[2 3 4]
數(shù)組相乘
a = np.arange(4).reshape((2,2))
print(a)
a * a
[[0 1]
[2 3]]
array([[0, 1],
[4, 9]])
矩陣乘法
np.dot(a,a)
array([[ 2, 3],
[ 6, 11]])
a_matrix = np.matrix(a)
a_matrix * a_matrix
matrix([[ 2, 3],
[ 6, 11]])
矩陣變換
#轉(zhuǎn)置
print(a,"\n")
a.T
[[0 1]
[2 3]]
array([[0, 2],
[1, 3]])
a.transpose()
array([[0, 2],
[1, 3]])
#共軛
c = np.matrix([[1+2j,2+2j],[3+4j,4+4j]])
print(c,"\n")
np.conjugate(c)
[[1.+2.j 2.+2.j]
[3.+4.j 4.+4.j]]
matrix([[1.-2.j, 2.-2.j],
[3.-4.j, 4.-4.j]])
#共軛轉(zhuǎn)置
c.H
matrix([[1.-2.j, 3.-4.j],
[2.-2.j, 4.-4.j]])
#獲取實(shí)部兰绣,虛部
np.real(c)
matrix([[1., 2.],
[3., 4.]])
np.imag(c)
matrix([[2., 2.],
[4., 4.]])
#獲取幅角
np.angle(c)
array([[1.10714872, 0.78539816],
[0.92729522, 0.78539816]])
#獲取絕對(duì)值
np.abs(c)
matrix([[2.23606798, 2.82842712],
[5. , 5.65685425]])