假定所有操作都事先导入numpy库
import numpy
1、判断向量或矩阵中是否存在某一元素
①向量
vector = numpy.array([5, 10, 15, 20]) vector == 10
结果为:array([False, True, False, False], dtype=bool)
②矩阵
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]]) matrix == 25
结果为:
array([[False, False, False], [False, True, False], [False, False, False]], dtype=bool)
若想取出向量和矩阵中结果为true的数
在向量中:
vector = numpy.array([5, 10, 15, 20]) equal_to_ten = (vector == 10) print(vector[equal_to_ten])
结果为:[10]
在矩阵中:
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]]) equal_to_twentyfive = (matrix[:,1] == 25) #将第二列中含有 25 的行赋值给equal_to_twentyfive print(matrix[equal_to_twentyfive, :]) #将第含有 25 的行中的所有元素输出
结果为:[[20 25 30]]
2、“与”(&)和“或”(|)
①&
vector = numpy.array([5, 10, 15, 20]) equal_to_ten_and_five = (vector == 10) & (vector == 5) print(equal_to_ten_and_five) 结果为:[False False False False]
②|
vector = numpy.array([5, 10, 15, 20]) equal_to_ten_and_five = (vector == 10)| (vector == 5) print(equal_to_ten_and_five) 结果为:[ True True False False]
3、类型转换
例:将 int 转换为 float 类型
vector = numpy.array([5, 10 ,15, 20]) print(vector.dtype) print(vector) vector = vector.astype(float) print(vector.dtype) print(vector)
结果为:
int32 [ 5 10 15 20] float64 [ 5. 10. 15. 20.]
4、最值与求和
①取向量和矩阵中的最值
vector = numpy.array([5, 10 ,15, 20]) vector.min() #取向量中的最小值
结果为:5
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]]) matrix.max() #取矩阵中的最大值
结果为:45
②矩阵按行(列)求和
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]]) matrix.sum(axis = 1) #按行求和
结果为:array([ 30, 75, 120])
`
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]]) matrix.sum(axis = 0) #按列求和
结果为:array([60, 75, 90])`