接上篇文章继续。 本章主要说明python中有索引切片功能,可以直接使用系统函数,也可以使用下标索引。
就是数组不同维度上,给出下标,获取索引的子空间
1. 普通索引获取ndarray对象中的部分元素:
- 使用系统函数slice(start,stop,step)
>>> a = np.arange(1,10)
>>> a
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s = slice(2,8,1)
>>> print(a[s])
[3 4 5 6 7 8]
>>> s = slice(2,8,2)
>>> print(a[s])
[3 5 7]
>>>
- 使用下标作为标识,一维的数据:
>>> a = np.arange(1,10)
>>> a[1:5:1]
array([2, 3, 4, 5])
>>> a[1:5:2]
array([2, 4])
>>> a[3]
4
>>> a[3:]
array([4, 5, 6, 7, 8, 9])
>>> a[3::2]
array([4, 6, 8])
- 二维数据(每个列表作为一个元素)
获取一个维度数据使用:获取整个维度数据,使用一个完整的对象使用下标
>>> a = np.arange(20).reshape(4,5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
>>> a[::2]
array([[ 0, 1, 2, 3, 4],
[10, 11, 12, 13, 14]])
>>> a[1:1]
array([], shape=(0, 5), dtype=int64)
>>> a[1:2]
array([[5, 6, 7, 8, 9]])
- 使用... 标识一个维度下的所有记录都选中:
>>> a = np.arange(20).reshape(4,5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
>>> a[...,2]
array([ 2, 7, 12, 17])
>>> a[2,...]
array([10, 11, 12, 13, 14])
2. 高级索引获取某个位置的元素:
- 使用列表对应ndarray对象中的元素
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
>>> a[[1,2,3],[2,3,4]]
array([ 7, 13, 19])
>>>
- 使用ndarray对象获取元素
>>> a
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]])
>>> i = np.array([[1,2],[3,4]],dtype='int')
>>> j = np.array([[2,1],[4,3]],dtype='int')
>>> a[i,j]
array([[ 8, 13],
[22, 27]])
- 使用普通索引使用的参数类型
>>> i = a[1:4,2:5]
>>> j = a[1:3,4:6]
>>> k = a[1,3,4,...]
>>> i
array([[ 8, 9, 10],
[14, 15, 16],
[20, 21, 22]])
>>> j
array([[10, 11],
[16, 17]])
>>> k
array([[ 6, 7, 8, 9, 10, 11],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29]])
- 布尔值类型的索引
>>> k[k>4]
array([ 6, 7, 8, 9, 10, 11, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29])
- 指定下标索引,包括正序和倒叙索引,多个索引数组(使用np.ix_)
>>> k
array([[ 6, 7, 8, 9, 10, 11],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29]])
>>> k[[1,2]]
array([[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29]])
>>> k[[-1,-2]]
array([[24, 25, 26, 27, 28, 29],
[18, 19, 20, 21, 22, 23]])
>>>
>>> k[np.ix_([1,2],[3,4])]
array([[21, 22],
[27, 28]])
- 缺省索引 不完全索引就是从多维数组中索引或者切片的一种方便方法。
>>> a = np.arange(0,100,10)
>>> a
array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
>>> b=a[:5]
>>> b
array([ 0, 10, 20, 30, 40])
>>> c = a[a>50]
>>> c
array([60, 70, 80, 90])
>>> a
array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
>>> b=np.where(a<=50)
>>> b
(array([0, 1, 2, 3, 4, 5]),)
>>> c=np.where(a>=50)
>>> c
(array([5, 6, 7, 8, 9]),)
>>> c=np.where(a>=50)[0]
>>> c
array([5, 6, 7, 8, 9])