用lis的值替换numpy索引数组的值

2024-05-19 00:21:19 发布

您现在位置:Python中文网/ 问答频道 /正文

假设您有一个numpy数组和一个列表:

>>> a = np.array([1,2,2,1]).reshape(2,2)
>>> a
array([[1, 2],
       [2, 1]])
>>> b = [0, 10]

我想替换数组中的值,以便1替换为0,2替换为10。

我在这里发现了一个类似的问题-http://mail.python.org/pipermail//tutor/2011-September/085392.html

但是使用这个解决方案:

for x in np.nditer(a):
    if x==1:
        x[...]=x=0
    elif x==2:
        x[...]=x=10

给我一个错误:

ValueError: assignment destination is read-only

我想那是因为我不能真正写入numpy数组。

注意,numpy数组的实际大小是514x504,列表的实际大小是8。


Tags: orgnumpyhttp列表forhtmlnpmail
3条回答

不是逐个替换值,而是可以重新映射整个数组,如下所示:

import numpy as np
a = np.array([1,2,2,1]).reshape(2,2)
# palette must be given in sorted order
palette = [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]]

Credit for the above idea goes to @JoshAdel。它比我原来的答案快得多:

import numpy as np
import random
palette = np.arange(8)
key = palette**2
a = 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 loop
In [112]: %timeit using_digitize()
100 loops, best of 3: 5.14 ms per loop

我想你需要的是

a[a==2] = 10 #replace all 2's with 10's

numpy中的只读数组可写:

nArray.flags.writeable = True

这将允许这样的分配操作:

nArray[nArray == 10] = 9999 # replace all 10's with 9999's

真正的问题不是赋值本身,而是可写标志。

相关问题 更多 >

    热门问题