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

Numpy查找具有相同值的组的索引

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

Numpy查找具有相同值的组的索引

我们可以做这样的事情,适用于任何通用数组-

def islandinfo(y, trigger_val, stopind_inclusive=True):    # Setup "sentients" on either sides to make sure we have setup    # "ramps" to catch the start and stop for the edge islands    # (left-most and right-most islands) respectively    y_ext = np.r_[False,y==trigger_val, False]    # Get indices of shifts, which represent the start and stop indices    idx = np.flatnonzero(y_ext[:-1] != y_ext[1:])    # Lengths of islands if needed    lens = idx[1::2] - idx[:-1:2]    # Using a stepsize of 2 would get us start and stop indices for each island    return list(zip(idx[:-1:2], idx[1::2]-int(stopind_inclusive))), lens

样品运行-

In [320]: yOut[320]: array([1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1])In [321]: islandinfo(y, trigger_val=1)[0]Out[321]: [(0, 2), (8, 9), (16, 19)]In [322]: islandinfo(y, trigger_val=0)[0]Out[322]: [(3, 7), (10, 15)]

另外,我们可以使用

diff
来获取切片后的比较结果,然后简单地用
2
列进行整形以替换步长大小的切片,从而给自己一个单线-

In [300]: np.flatnonzero(np.diff(np.r_[0,y,0])!=0).reshape(-1,2) - [0,1]Out[300]: array([[ 0,  2],       [ 8,  9],       [16, 19]])


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

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

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