一:判断array中的值是否满足条件
vector = numpy.array([10, 20, 30, 40, 50]) equal_to_ten = (vector == 10) print(equal_to_ten)
打印结果:
[ True False False False False]
1.返回真实值:
print(vector[equal_to_ten])
打印结果:
[10]
2.在二维数组中的应用:bool可值当做索引
matrix = numpy.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) print(matrix[:, 1]) #返回第二列 second_column_25 = (matrix[:, 1] == 5) #判断第二列中的值是否等于5 print(second_column_25) print(matrix[second_column_25, :]) #打印第二列等于5那一行中所有的值
打印结果:
[2 5 8]
[False True False]
[[4 5 6]]
3.多条件判断
vector = numpy.array([10, 20, 30, 40, 50]) equal_to_ten_and_tewnty = (vector == 10) & (vector == 20) print(equal_to_ten_and_tewnty)
打印结果:[False False False False False]
vector = numpy.array([10, 20, 30, 40, 50]) equal_to_ten_or_twenty = (vector == 10) | (vector == 20) print(equal_to_ten_or_twenty)打印结果:[ True True False False False]
应用:
vector = numpy.array([10, 20, 30, 40, 50]) equal_to_ten_or_twenty = (vector == 10) | (vector == 20) vector[equal_to_ten_or_twenty] = 5 print(vector)
打印结果:[ 5 5 30 40 50]
二:dtype的类型转换
vector = numpy.array([1, 2, 3, 4]) print(vector.dtype) print(vector) vector = vector.astype(float) print(vector.dtype) print(vector) vector = vector.astype(str) print(vector.dtype) print(vector)
打印结果:
int32
float64
[ 1. 2. 3. 4.]
<U32
['1.0' '2.0' '3.0' '4.0']
三:numpy.array的属性
1.更多请参考:http://blog.youkuaiyun.com/cjgs45/article/details/79517275
print(vector.min())
print(vector.max())
2.按行求和
matrix = numpy.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) print(matrix.sum(axis=1)) #axis=0则为按列求和打印结果:
[ 6 15 24]