# NumPy - 高级索引

## 整数索引

```import numpy as np

x = np.array([[1, 2], [3, 4], [5, 6]])
y = x[[0,1,2], [0,1,0]]
print y```

`[1  4  5]`

```import numpy as np
x = np.array([[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8],[ 9, 10, 11]])

print 'Our array is:'
print x
print '\n'

rows = np.array([[0,0],[3,3]])
cols = np.array([[0,2],[0,2]])
y = x[rows,cols]

print 'The corner elements of this array are:'
print y```

```Our array is:
[[ 0  1  2]
[ 3  4  5]
[ 6  7  8]
[ 9 10 11]]

The corner elements of this array are:
[[ 0  2]
[ 9 11]] ```

```import numpy as np
x = np.array([[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8],[ 9, 10, 11]])

print 'Our array is:'
print x
print '\n'

# slicing
z = x[1:4,1:3]

print 'After slicing, our array becomes:'
print z
print '\n'

# 使用列的高级索引
y = x[1:4,[1,2]]

print 'Slicing using advanced index for column:'
print y```

```Our array is:
[[ 0  1  2]
[ 3  4  5]
[ 6  7  8]
[ 9 10 11]]

After slicing, our array becomes:
[[ 4  5]
[ 7  8]
[10 11]]

Slicing using advanced index for column:
[[ 4  5]
[ 7  8]
[10 11]] ```

## 布尔数组索引

```import numpy as np
x = np.array([[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8],[ 9, 10, 11]])

print 'Our array is:'
print x
print '\n'

# 现在我们将打印大于 5 的元素
print 'The items greater than 5 are:'
print x[x > 5]```

```Our array is:
[[ 0  1  2]
[ 3  4  5]
[ 6  7  8]
[ 9 10 11]]

The items greater than 5 are:
[ 6  7  8  9 10 11] ```

```import numpy as np
a = np.array([np.nan, 1,2,np.nan,3,4,5])
print a[~np.isnan(a)]```

`[ 1.   2.   3.   4.   5.] `

```import numpy as np
a = np.array([1, 2+6j, 5, 3.5+5j])
print a[np.iscomplex(a)]```

`[2.0+6.j  3.5+5.j] `

### 相关文章

Linux实战技能100讲 -〔尹会生 - 〕

MongoDB高手课 -〔唐建法（TJ） - 〕

Pandas 函数基于单列创建多列