Using NumPy(使用 NumPy)¶
NumPy 是一个用于处理大规模数组型数据的 Python 库,也是 array-based NumPy trace step templates(基于数组的 NumPy trace step 模板) 的技术基础。可以通过以下链接访问 NumPy 官方手册: https://docs.scipy.org/doc/numpy/index.html
特别推荐将快速入门教程作为上手资料: https://docs.scipy.org/doc/numpy/user/quickstart.html
此外,下面重点说明几个与 trace analysis 特别相关的方面。
Boolean Operators(布尔运算符)¶
无论是表达式 if arr: print('hallo'),还是语句 bool(arr),都不能用来检查 NumPy 数组是否为空,或者是否包含 True 值。对此必须使用 NumPy 提供的相应机制,如下例所示:
import numpy as np
arr = np.array([3, 1, -2, 0], dtype=np.float64)
# Is arr valid?
if isinstance(arr, np.ndarray):
print('arr is a valid NumPy array')
# Is arr empty?
if len(arr) > 0:
print('arr is not empty')
# Handling of Boolean values
positive = arr >= 0 # comparison with zero is carried out element by element and stored in new array: [True, True, False, True]
print(np.all(positive)) # False, as not all elements of positive are True
print(np.any(positive)) # True, as positive is True in at least one (three, in fact) element
注意
np.nan(“not a number”)的布尔值是 True!因此,表达式 np.all(np.array([0.1, 3.0, np.nan])) 的求值结果为 True。
Masking(掩码)¶
Python 的索引/切片机制同样可以与 NumPy 配合使用,以访问单个值或部分数组:
import numpy as np
arr = np.arange(10) # [0 1 2 3 4 5 6 7 8 9]
print(arr[3:5]) # [3, 4]
print(arr[:4]) # [0, 1, 2, 3]
print(arr[8:]) # [8, 9]
不过,NumPy 还提供了更强大的子集选择方式。一方面,可以通过指定布尔掩码来选择特定值;另一方面,也可以通过索引数组指定所需元素。
布尔掩码:所有值 >= 阈值
import numpy as np
arr = np.array([0, 3, 7, 13, 10, 11, 12.5, 15])
threshold = 12
mask = arr >= threshold # Boolean mask: [False, False, False, True, False, False, True, True]
print(arr[mask]) # [13, 12.5, 15]
布尔掩码:时间区间内的所有信号值
import numpy as np
values = np.array([100, 200, 300, 400, 500])
timestamps = np.arange(5.0) # [0.0, 1.0, 2.0, 3.0, 4.0]
# All values from the closed time interval between 1.0 and 2.5
mask = np.logical_and(1.0 <= timestamps, timestamps <= 2.5)
print(values[mask]) # [200, 300]
索引数组:信号从 20 变化到 30
import numpy as np
values = np.array([0, 10, 20, 30, 40])
timestamps = np.arange(5.0) # [0.0, 1.0, 2.0, 3.0, 4.0]
# Create Boolean mask that contains True where a value of 20 is followed by 30
boolMask = np.logical_and(values[:-1] == 20, values[1:] == 30) # [False, False, True, False]
# Create corresponding index array, Attention: boolMask contains one element less than values
indexArr = np.arange(values.shape[0] - 1)[boolMask] # [2]
# indexArr refers to the position of 20 by now, but shall refer to the change from 20 to 30
indexArr = indexArr + 1 # [3]
# Alternative: numpy.where()
indexArr = np.where(boolMask)[0] + 1 # [3]
print(timestamps[indexArr]) # [3.0]
print(values[indexArr]) # [30]