一、使用索引提取值
print("---------------書寫格式2------------------------") # dtype="U75" :表示以字符串類型導入(75是導入的字符個數為75) # skip_header=1 :表示從txt的第1行導入,即表頭(第0行)不導入 world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimiter=",", dtype="U75", skip_header=1) print(world_alcohol) print("-----------使用索引提取單個值------------------") uruguay_other_1986 = world_alcohol[1,4] # 提取第1行第4列的值 third_country = world_alcohol[2,2] # 提取第2行第2列的值 print (uruguay_other_1986) print (third_country)
結果圖:
提取值后結果:
二、使用切片提取一維數組、多維數組數據
print("---------------使用切片提取一維數組內的數據-----------------") vector = numpy.array([5, 10, 15, 20]) print(vector[0:3]) # 一維數組:提取第0列到第2列所有的值,返回:[ 5 10 15] print("----------------使用切片提取二維數組內的數據--------------------------") matrix = numpy.array([ [5, 10, 15], [20, 25, 30], [35, 40, 45] ]) print(matrix[:,1]) # 二維數組:提取所有行的第1列的值,返回:[10 25 40] print("---------") print(matrix[:,0:2]) # 提取所有行的第0列導第1列的值 print("---------") print(matrix[1:3,0:2]) # 提取第1行到第2行的第0列到第1列的值
提取后結果