1.7.花式索引 2018/11/11
==================================================================
1.说明
# 1)NumPy数组可用切片进行索引
# 2)可用布尔或整数数组(掩码)进行索引.这种方法称为花式索引.
# .3)花式索引跟切片不一样,它创建副本而不是视图。
用法:
a[ [bool or int]]
==================================================================
# 1.1.使用布尔掩码
np.random.seed(3)
np.random.randint(0, 10, 8) # array([8, 9, 3, 8, 8, 0, 5, 3])
mask = (a % 2 == 0) # array([True, False, False,True,True,True,False,False])
b= a[mask] # 等价a[a%2==0]
b # array([8, 8, 8, 0])
#1.2.为子数组分配新值:
a[a % 2 == 0] = -1
a # array([-1, 9, 3, -1, -1, -1, 5, 3])
===================================================================
# 2.1.使用整数数组进行索引
a = np.arange(0, 100, 10)
a # array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
a[[2, 3, 2, 4, 2]] # note: [2, 3, 2, 4, 2] is a Python list
# array([20, 30, 20, 40, 20])
# 用整数数组进行索引来创建新数组,新数组形状与整数数组形状相同:
----------------------------------------------
a = np.arange(10)
idx = np.array([[3, 4], [9, 7]])
idx.shape # (2, 2)
a[idx] #array([[3, 4],[9, 7]])
----------------------------------------------
# 一次传入多个索引数组:
arr= np.arange(32).reshape((8, 4))
arr #array( [[ 0, 1, 2, 3], [ 4, 5, 6, 7],[ 8, 9, 10, 11], [12, 13, 14, 15],
[16, 17, 18, 19],[20, 21, 22, 23], [24, 25, 26, 27],[28, 29, 30, 31]])
arr[[1, 5, 7, 2], [0, 3, 1, 2]]#array([ 4, 23, 29, 10])终选元素(1,0),(5,3),(7,1),(2,2)
-----------------------------------------------
# ix_函数将两个一维数组转换为一个用于选取方形区域的索引器:
arr[np.ix_([1, 5, 7, 2], [0, 3, 1, 2])]
arr[[1, 5, 7, 2]][:,[0, 3, 1, 2]] # 等价于上面
# array( [[ 4, 7, 5, 6],
[20, 23, 21, 22],
[28, 31, 29, 30],
[ 8, 11, 9, 10]])
------------------------------------------------
# 2.2.可以使用此类索引分配新值:
a[[9, 7]] = -100
a # array([0,10,20,30,40,50,60,-100,80,-100])
=====================================================================