以下代码是基于python3.5.0
import numpy # -----------------------判断数组中是否存在特定值------------------------------ vector = numpy.array([5, 10, 15, 20]) print(vector == 10) # 判断数组中有没有10,返回布尔值[False True False False] # -----------------------判断矩阵中是否存在特定值------------------------------ matrix = numpy.array([ [5, 10, 15], [20, 25, 30], [35, 40, 45]]) # 返回array([[False, False, False],[False, True, False],[False, False, False]], dtype=bool) matrix == 25 # -----------------------判断数组中是否存在特定值,并打印出值------------------------------ vector = numpy.array([5, 10, 15, 20]) equal_to_ten = (vector == 10) print(equal_to_ten) # [False True False False] print(vector[equal_to_ten]) # 10 # -----------------------判断矩阵中是否存在特定值------------------------------ matrix = numpy.array([ [5, 10, 15], [20, 25, 30], [35, 40, 45] ]) second_column_25 = (matrix[:,1] == 25) # 判断第二列有没有等于25的值,返回值为布尔值 print(second_column_25) # [False True False] print(matrix[second_column_25, :]) # [[20 25 30]] 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_or_five = (vector == 10) | (vector == 5) # [True True False False] vector[equal_to_ten_or_five] = 50 # 把为true的位置赋值为50 print(vector) # [50, 50, 15, 20] # ------------------判断矩阵中是否存在某个值,把特定位置的值进行重新赋值---------------------- matrix = numpy.array([ [5, 10, 15], [20, 25, 30], [35, 40, 45] ]) second_column_25 = matrix[:,1] == 25 print(second_column_25) # [False True False] matrix[second_column_25, 1] = 10 # 把第2行第2列赋值为10 print(matrix) # -------------------类型装换------------------- vector = numpy.array(["1", "2", "3"]) print(vector.dtype) # S1 print(vector) # ['1' '2' '3'] vector = vector.astype(float) print(vector.dtype) # float64 print(vector) # [ 1. 2. 3.] # --------------------求和---------------------- vector = numpy.array([5, 10, 15, 20]) vector.sum() # 50 # -------------------按行求和axis=1-------------------- matrix = numpy.array([ [5, 10, 15], [20, 25, 30], [35, 40, 45] ]) matrix.sum(axis=1) # array([ 30, 75, 120]) # -------------------按列求和axis=0-------------------- matrix = numpy.array([ [5, 10, 15], [20, 25, 30], [35, 40, 45] ]) matrix.sum(axis=0) # array([60, 75, 90]) # ------------------------自己练习--------------------------- #replace nan value with 0 world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimiter=",") #print world_alcohol is_value_empty = numpy.isnan(world_alcohol[:,4]) #print is_value_empty world_alcohol[is_value_empty, 4] = '0' alcohol_consumption = world_alcohol[:,4] alcohol_consumption = alcohol_consumption.astype(float) total_alcohol = alcohol_consumption.sum() average_alcohol = alcohol_consumption.mean() print(total_alcohol) print(average_alcohol)