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

如何在numpy ndarray中查找最频繁的值?

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

如何在numpy ndarray中查找最频繁的值?

要查找的平面阵列,使用最频繁的价值

unique
bincount
并且
argmax

arr = np.array([5, 4, -2, 1, -2, 0, 4, 4, -6, -1])u, indices = np.unique(arr, return_inverse=True)u[np.argmax(np.bincount(indices))]

要使用多维数组的工作,我们不必操心

unique
,但我们确实需要使用
apply_along_axis
bincount

arr = np.array([[5, 4, -2, 1, -2, 0, 4, 4, -6, -1],     [0, 1,  2, 2,  3, 4, 5, 6,  7,  8]])axis = 1u, indices = np.unique(arr, return_inverse=True)u[np.argmax(np.apply_along_axis(np.bincount, axis, indices.reshape(arr.shape),          None, np.max(indices) + 1), axis=axis)]

使用您的数据:

data = np.array([   [[ 0,  1,  2,  3,  4],    [ 5,  6,  7,  8,  9],    [10, 11, 12, 13, 14],    [15, 16, 17, 18, 19]],   [[ 0,  1,  2,  3,  4],    [ 5,  6,  7,  8,  9],    [10, 11, 12, 13, 14],    [15, 16, 17, 18, 19]],   [[40, 40, 42, 43, 44],    [45, 46, 47, 48, 49],    [50, 51, 52, 53, 54],    [55, 56, 57, 58, 59]]])axis = 0u, indices = np.unique(arr, return_inverse=True)u[np.argmax(np.apply_along_axis(np.bincount, axis, indices.reshape(arr.shape),          None, np.max(indices) + 1), axis=axis)]array([[ 0,  1,  2,  3,  4],       [ 5,  6,  7,  8,  9],       [10, 11, 12, 13, 14],       [15, 16, 17, 18, 19]])

NumPy
1.2,真的吗?您可以

np.unique(return_inverse=True)
使用进行合理有效的估算
np.searchsorted
(这是一个额外的O(
n log n ),因此不应显着改变性能):

u = np.unique(arr)indices = np.searchsorted(u, arr.flat)


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

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

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