花式索引
花式索引是Numpy术语,它指的是利用整数数组进行索引,假设我们有一个数组8×4的数组。
Note:花式索引和切片不一样,它总数将数组复制到新数组中去。
1 #!/usr/bin/env python 2 #-*-coding:utf-8-*- 3 ''' 4 Description:初学numpy(四)--花式索引 5 Created on 2015年10月8日 6 @author: zenwan 7 @version: 8 ''' 9 import numpy as np 10 from pprint import pprint 11 12 arr = np.empty((8,4),dtype=np.int) 13 for i in range(8): 14 arr[i] = i**2 15 pprint(arr) 16 17 #花式索引:传入一个指定顺序的整数列表或者ndarray 18 arr_tmp01 = arr[[1,3,4,6]] 19 arr_tmp02 = arr[[-1,-2,-5,-7]] 20 pprint(arr_tmp01) 21 pprint(arr_tmp02) 22 23 #一次传入多个索引数组 24 arr1 = np.arange(32).reshape((8,4)) 25 pprint(arr1) 26 pprint(arr1[[1,2,3,4],[0,1,2,3]])#最终选出(1,0),(2,1),(3,2),(4,3)位置的元素 27 pprint(arr1[[1,2,3,4]][:,[0,1]])
运行结果:
1 array([[ 0, 0, 0, 0], 2 [ 1, 1, 1, 1], 3 [ 4, 4, 4, 4], 4 [ 9, 9, 9, 9], 5 [16, 16, 16, 16], 6 [25, 25, 25, 25], 7 [36, 36, 36, 36], 8 [49, 49, 49, 49]]) 9 array([[ 1, 1, 1, 1], 10 [ 9, 9, 9, 9], 11 [16, 16, 16, 16], 12 [36, 36, 36, 36]]) 13 array([[49, 49, 49, 49], 14 [36, 36, 36, 36], 15 [ 9, 9, 9, 9], 16 [ 1, 1, 1, 1]]) 17 array([[ 0, 1, 2, 3], 18 [ 4, 5, 6, 7], 19 [ 8, 9, 10, 11], 20 [12, 13, 14, 15], 21 [16, 17, 18, 19], 22 [20, 21, 22, 23], 23 [24, 25, 26, 27], 24 [28, 29, 30, 31]]) 25 array([ 4, 9, 14, 19]) 26 array([[ 4, 5], 27 [ 8, 9], 28 [12, 13], 29 [16, 17]])