numpy.choose 32选择限制

时间:2012-07-19 22:19:02

标签: python numpy

很低,看到升级到1.5.1后,我在numpy.choose中遇到了回归。过去的版本(和数字)支持,据我所知,无限数量的潜在选择。 “新”选项限制为32. Here is a post,其他用户对回归感到遗憾。

我有一个包含100个选项(0-99)的列表,我用它来修改数组。作为一种解决方法,我使用以下代码。可以理解,它比使用选择慢7倍。我不是一名C程序员,虽然我想修复这个numpy问题,但我想知道其他可能更快的解决方法是什么。想法?

d={...} #A dictionary with my keys and their new mappings
for key, value in d.iteritems():
    array[array==key]=value 

3 个答案:

答案 0 :(得分:2)

我认为d的密钥099。在这种情况下,解决方案非常简单。首先,以d的方式在NumPy数组values中写入d[i] == values[i]的值 - 无论如何,这似乎是这些值的自然数据结构。然后,您可以使用

替换的值访问新数组
values[array]

如果您想修改array,只需执行

即可
array[:] = values[array]

答案 1 :(得分:0)

我不确定效率并且它不在原地(nb:我经常不使用numpy - 因此有点生锈):

import numpy as np

d = {0: 5, 1: 3, 2: 20}
data = np.array([[1, 0, 2], [2, 1, 1], [1, 0, 1]])
new_data = np.array([d.get(i, i) for i in data.flat]).reshape(data.shape) # adapt for list/other

答案 2 :(得分:0)

在Numpy文档中,有一个示例显示select函数的简化版本。

  

[...]此功能不像它看起来那么简单   以下代码描述(在ndi = numpy.lib.index_tricks下面):

np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)]).

请参见https://docs.scipy.org/doc/numpy/reference/generated/numpy.choose.html

将其放入函数可能如下所示:

import numpy

def choose(selector, choices):
    """
    A simplified version of the numpy choose function to workaround the 32
    choices limit.
    """
    return numpy.array([choices[selector[idx]][idx] for idx in numpy.lib.index_tricks.ndindex(selector.shape)]).reshape(selector.shape)

我不确定这是如何转换为效率的,与numpy.choose函数相比,何时确切地将其分解。但这对我来说很好。请注意,修补功能假定选项中的条目是可下标的。