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

有效地计算NumPy中唯一子数组的出现次数?

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

有效地计算NumPy中唯一子数组的出现次数?

问题指出输入数组的形状

(128, 36,8)
,我们有兴趣在
8
最后一个维度中找到长度唯一的子数组。因此,我假设唯一性是沿着合并在一起的前两个维度。让我们假设
A
作为输入3D阵列。

获取唯一子数组的数量

# Reshape the 3D array to a 2D array merging the first two dimensionsAr = A.reshape(-1,A.shape[2])# Perform lex sort and get the sorted indices and xy pairssorted_idx = np.lexsort(Ar.T)sorted_Ar =  Ar[sorted_idx,:]# Get the count of rows that have at least one TRUE value # indicating presence of unique subarray thereunq_out = np.any(np.diff(sorted_Ar,axis=0),1).sum()+1

样品运行-

In [159]: A # A is (2,2,3)Out[159]: array([[[0, 0, 0],        [0, 0, 2]],       [[0, 0, 2],        [2, 0, 1]]])In [160]: unq_outOut[160]: 3

获取唯一子数组的出现次数

# Reshape the 3D array to a 2D array merging the first two dimensionsAr = A.reshape(-1,A.shape[2])# Perform lex sort and get the sorted indices and xy pairssorted_idx = np.lexsort(Ar.T)sorted_Ar =  Ar[sorted_idx,:]# Get IDs for each element based on their uniquenessid = np.append([0],np.any(np.diff(sorted_Ar,axis=0),1).cumsum())# Get counts for each ID as the final outputunq_count = np.bincount(id)

样品运行-

In [64]: AOut[64]: array([[[0, 0, 2],        [1, 1, 1]],       [[1, 1, 1],        [1, 2, 0]]])In [65]: unq_countOut[65]: array([1, 2, 1], dtype=int64)


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

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

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