一个numpy数组如何被另一个具有其他维度的numpy数组替换?

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

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

我有一个小的numpy问题,我试图用B的值替换a的值。 见MWE:

t = np.arange(65,70,2)
>>array([65, 67, 69])

b = np.random.randint(3,size=20)
>>array([2, 2, 1, 2, 1, 2, 2, 1, 1, 0, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2])

现在b应该被t屏蔽,这样2对应于t的第三个元素,0对应于t的第一个元素

使用numpy最有效的方法是什么


Tags: 方法numpy元素sizenprandomarray屏蔽
2条回答

方式1

为了便于使用,您可以这样替换b的项:

for i in range(3):
    b[b==i] = t[i]

这很公平,但效率不高,特别是如果你使用大量的索引

方式2

如果您想优化它,您需要使用分组,就像我讨论的in this post。借用Divakar的answernumpy唯一的解决方案需要更深入的理解:

b = np.array([2, 2, 1, 2, 1, 2, 2, 1, 1, 0, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2])
sidx = np.argsort(b) #indices that would sort an array
bs = b[sidx] #sorted array
# locations of changings in sorted array, [ 0,  3,  7, 20] in this case:
split_idx = np.flatnonzero(np.r_[True,bs[:-1]!=bs[1:],True])
indices = [sidx[i:j] for (i,j) in zip(split_idx[:-1], split_idx[1:])]

索引是数组的列表[ 9, 17, 15][2, 4, 7, 8][16, 14, 13, 12, 0, 10, 18, 6, 5, 3, 1, 11, 19],相当于b==0b==1b==2,因此您现在可以这样使用它们:

for i in range(len(indices)):
    b[indices[i]] = t[i]

方式3

这是我发现的最有效的方法,但在这里numpy是不够的:

import pandas as pd
indices = pd.DataFrame(b).groupby([0]).indices.values()
for i in range(len(indices)):
    b[indices[i]] = t[i]

您可以使用列表理解:

[t[b_elem] for b_elem in b]

相关问题 更多 >

    热门问题