一、算数判断运算取值
import numpy print("-------------一维数组运算取值------------------") vector = numpy.array([5, 10, 15, 20]) # vector == 10 equal_to_ten = (vector == 10) print (equal_to_ten) # 返回:[False True False False] print(vector[equal_to_ten]) # 返回:[10] print("---------------二维数组运算取值----------------------") matrix = numpy.array([ [5, 10, 15], [20, 25, 30], [35, 40, 45] ]) print(matrix == 25) print("------------") second_column_25 = (matrix[:,1] == 25) print (second_column_25) # 返回:[False True False],第1个是真,可用来取值 print(matrix[second_column_25, :]) # 提取第1行所有列,返回:[[20 25 30]] print("------替换值--------") matrix[second_column_25, 1] = 10 # 将提取到的第1行第1列的值替换为10 print (matrix)
结果图:
二、使用 “&”、“|” 进行运算取值、替换值
print("----------------'&' :表示和-----------------") 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] print("----------'|' :表示或----------------------") equal_to_ten_or_five = (vector == 10) | (vector == 5) print (equal_to_ten_or_five) # 返回:[ True True False False] print(vector[equal_to_ten_or_five]) # 返回True的值 vector[equal_to_ten_or_five] = 50 # 将返回True的值(即提取到的值)替换为50 print(vector)
结果图: