栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python:对齐NumPy数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python:对齐NumPy数组

这里有一个量化的方法,通过启发

this other post
和推广到覆盖
non-zeros
所有四个方向-

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

样品运行

In [473]: a # input arrayOut[473]: array([[1, 0, 2, 0],       [3, 0, 4, 0],       [5, 0, 6, 0],       [6, 7, 0, 8]])In [474]: justify(a, axis=0, side='up')Out[474]: array([[1, 7, 2, 8],       [3, 0, 4, 0],       [5, 0, 6, 0],       [6, 0, 0, 0]])In [475]: justify(a, axis=0, side='down')Out[475]: array([[1, 0, 0, 0],       [3, 0, 2, 0],       [5, 0, 4, 0],       [6, 7, 6, 8]])In [476]: justify(a, axis=1, side='left')Out[476]: array([[1, 2, 0, 0],       [3, 4, 0, 0],       [5, 6, 0, 0],       [6, 7, 8, 0]])In [477]: justify(a, axis=1, side='right')Out[477]: array([[0, 0, 1, 2],       [0, 0, 3, 4],       [0, 0, 5, 6],       [0, 6, 7, 8]])


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517594.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号