使用索引数组进行索引
可以使用索引数组来访问数组的特定元素,而不是使用循环。这在处理多维数组时特别有用。
indices = np.array([1, 3, 0])
arr = np.array([10, 20, 30, 40, 50])
selected_elements = arr[indices] # [20, 40, 10]
避免循环np.vectorize()
如果有一个本质上不是矢量化的函数,可以用它来使np.vectorize()有效地处理数组。
def non_vectorized_func(x):
return x + 2
arr = np.array([10, 20, 30, 40, 50])
vectorized_func = np.vectorize(non_vectorized_func)
result = vectorized_func(arr)
条件赋值np.where()
用于执行条件赋值,根据条件替换元素。np.where()
arr = np.array([1, 2, 3, 4, 5])
new_arr = np.where(arr > 2, arr, 0) # [0, 0, 3, 4, 5]
高级广播
广播可以创造性地用于执行涉及多个阵列的复杂操作。
a = np.arange(6).reshape(3, 2)
b = np.array([10, 20, 30])
result = a + b[:, np.newaxis] # Broadcasting along both dimensions
直方图np.histogram()
使用 计算数组元素的直方图。np.histogram()
arr = np.array([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
hist, bins = np.histogram(arr, bins=4, range=(1, 5))
优化内存使用np.memmap
当处理不适合内存的大型数据集时,可以使用内存映射数组 using 从磁盘访问数据,就像在内存中一样。np.memmap()
mmap_array = np.memmap('data.dat', dtype='float32', mode='r+', shape=(1000000,))
自定义通用函数
可以为专用操作创建自己的自定义 ufunc。这对于封装复杂的计算非常有用。
def custom_function(x):
# Define your operation
return x ** 2 + 2 * x + 1
custom_ufunc = np.frompyfunc(custom_function, 1, 1)
result = custom_ufunc(arr)
屏蔽阵列
屏蔽数组允许您处理具有缺失值或无效值的数据
arr = np.ma.masked_array([1, 2, 3, 4, 5], mask=[False, True, False, False, True])