将非零元素对齐到特定一侧(通常在搜索中有用)是一种常见操作,可以直接对 NumPy 数组完成。以下是如何实现的 -
import numpy as np def justify(a, invalid_val=0, axis=1, side='left'): """ Justifies a 2D array Parameters ---------- A : ndarray Input array to be justified axis : int Axis along which justification is to be made side : str Direction of justification. It could be 'left', 'right', 'up', 'down' It should be 'left' or 'right' for axis=1 and 'up' or 'down' for axis=0. """ if invalid_val is np.nan: mask = ~np.isnan(a) else: mask = a!=invalid_val justified_mask = np.sort(mask,axis=axis) if (side=='up') | (side=='left'): justified_mask = np.flip(justified_mask,axis=axis) out = np.full(a.shape, invalid_val) if axis==1: out[justified_mask] = a[mask] else: out.T[justified_mask.T] = a.T[mask.T] return out
上面的代码片段可以沿选定的轴在四个可能方向中的任何一个方向对齐 2D 数组 -
# sample input array a = np.array([[1, 0, 2, 0], [3, 0, 4, 0], [5, 0, 6, 0], [0, 7, 0, 8]]) # shift to left print(justify(a, axis=0, side='up')) # shift to down print(justify(a, axis=0, side='down')) # shift to left print(justify(a, axis=1, side='left')) # shift to right print(justify(a, axis=1, side='right'))
以上是如何有效地证明 NumPy 数组的非零元素合理?的详细内容。更多信息请关注PHP中文网其他相关文章!