【Python】【NumPy】学习笔记
索引
单维切片
与python中的切片一样,slice切片和中括号切片,不包括停止索引stop:
- slice(start,stop,step)
-
start:stop:step
多维切片
切片+逗号+冒号/省略号。
python多维数组不能用多维索引/逗号,但numpy可以:
python
# x=[[1,2,3],[4,5,6],[7,8,9]]
# print(x[...,1]) # TypeError: list indices must be integers or slices, not tuple
x=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(x[...,1]) # [2 5 8]
省略号可以替换成冒号
整数索引
整数数组索引是指使用一个数组来访问另一个数组的元素:[第一维索引,第二维索引,第三维索引,...]
二维数组常见:[行索引,列索引]
python
import numpy as np
x = np.array([[1, 2], [3, 4], [5, 6]])
# 获取数组中 (0,0),(1,1) 和 (2,0) 位置处的元素。
y = x[[0,1,2], [0,1,0]]
# 结果:[1 4 5]
x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])
# 取这个数组的四个角元素
rows = np.array([[0,0],[3,3]])
cols = np.array([[0,2],[0,2]])
y = x[rows,cols]
# 索引:(0,0),(0,2),(3,0),(3,2)
print(x)
print(y)
'''
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[ 0 2]
[ 9 11]]
'''
a = np.array([[1,2,3], [4,5,6],[7,8,9]])
b = a[1:3, 1:3]
c = a[1:3,[0,2]]
d = a[...,1:]
print(b)
'''
[[5 6]
[8 9]]
'''
print(c)
'''
[[4 6]
[7 9]]
'''
print(d)
'''
[[2 3]
[5 6]
[8 9]]
'''
布尔索引
布尔索引通过布尔运算(如:比较运算符)来获取符合指定条件的元素的数组。
python
x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8]])
print(x)
'''
[[0 1 2]
[3 4 5]
[6 7 8]]
'''
print(x[x>3])
'''
[4 5 6 7 8]
'''
"""
以下几种多条件写法都会报错:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
"""
print(x[3 < x < 7])
print(x[x > 3 and x < 7])
print(x[x > 3 & x < 7])
print(x[(x > 3) and (x < 7)])
"""
正确写法:
"""
print(x[(x > 3) & (x < 7)]) # [4 5 6]
print(x[(x < 2) | (x > 3) & (x < 7)]) # [0 1 4 5 6]
print(x[np.logical_and(x > 3, x < 7)])
print(x[np.logical_or(x < 2, np.logical_and(x > 3, x < 7))])
a = np.array([np.nan, 1,2,np.nan,3,4,5])
print (a)
'''
[nan 1. 2. nan 3. 4. 5.]
'''
# 用 ~(取补运算符)过滤 NaN
print (a[~np.isnan(a)])
'''
[1. 2. 3. 4. 5.]
'''
a = np.array([1, 2 + 6j, 5, 3.5 + 5j])
print(a)
'''
[1. +0.j 2. +6.j 5. +0.j 3.5+5.j]
'''
# 过滤掉非复数元素
print(a[np.iscomplex(a)])
'''
[2. +6.j 3.5+5.j]
'''