一、使用索引提取值
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列的值
提取后结果