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

用列表的值替换numpy索引数组的值

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

用列表的值替换numpy索引数组的值

不必一一替换值,而是可以像这样重新映射整个数组:

import numpy as npa = np.array([1,2,2,1]).reshape(2,2)# palette must be given in sorted orderpalette = [1, 2]# key gives the new values you wish palette to be mapped to.key = np.array([0, 10])index = np.digitize(a.ravel(), palette, right=True)print(key[index].reshape(a.shape))

产量

[[ 0 10] [10  0]]

以上想法归功于@JoshAdel。它比我的原始答案快得多:

import numpy as npimport randompalette = np.arange(8)key = palette**2a = np.array([random.choice(palette) for i in range(514*504)]).reshape(514,504)def using_unique():    palette, index = np.unique(a, return_inverse=True)    return key[index].reshape(a.shape)def using_digitize():    index = np.digitize(a.ravel(), palette, right=True)    return key[index].reshape(a.shape)if __name__ == '__main__':    assert np.allclose(using_unique(), using_digitize())

我以这种方式对两个版本进行了基准测试:

In [107]: %timeit using_unique()10 loops, best of 3: 35.6 ms per loopIn [112]: %timeit using_digitize()100 loops, best of 3: 5.14 ms per loop


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

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

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