用NumPy数组替换值

4
我有两个numpy数组,都是M x N大小。X包含随机值。Y包含真/假值。数组A包含需要替换为-1的X中行的索引。我只想替换Y为真的值。
下面是一些代码来实现这个功能:
M=30
N=40
X = np.zeros((M,N))  # random values, but 0s work too
Y = np.where(np.random.rand(M,N) > .5, True, False)
A=np.array([ 7,  8, 10, 13]), # in my setting, it's (1,4), not (4,)
for i in A[0]:
    X[i][Y[A][i]==True]=-1

然而,我实际上只想替换其中的一些条目。列表B包含每个A中索引需要替换的数量。它已经排序好了,因此A [0] [0]对应于B [0]等等。此外,如果A [i] = k,则Y中相应的行至少有k个true。

B = [1,2,1,1]

然后对于每个索引 i(在循环中),

X[i][Y[A][i]==True][0:B[i]] = -1

这并不起作用。有什么解决方法吗?

2个回答

1

不清楚您想要做什么,以下是我的理解:

import numpy as np
m,n = 30,40
x = np.zeros((m,n))
y = np.random.rand(m,n) > 0.5    #no need for where here
a = np.array([7,8,10,13])
x[a] = np.where(y[a],-1,x[a])    #need where here

没错,但我实际上并不想让它们全部被替换——我需要将第一个B替换掉。如果B[0] = 2,那么只想要第一个y[7][0:2] 被替换成-1,而不是所有的y[7]都被改变。如果B[1] = 3,则将y[8][0:3]改为-1。 - Kevin

1

很遗憾,我没有一个优雅的答案;不过这个方法可以解决问题:

M=30
N=40
X = np.zeros((M,N))  # random values, but 0s work too
Y = np.where(np.random.rand(M,N) > .5, True, False)
A=np.array([ 7,  8, 10, 13]), # in my setting, it's (1,4), not (4,)
B = [1,2,1,1]

# position in row where X should equal - 1, i.e. X[7,a0], X[8,a1], etc
a0=np.where(Y[7]==True)[0][0]
a1=np.where(Y[8]==True)[0][0]
a2=np.where(Y[8]==True)[0][1]
a3=np.where(Y[10]==True)[0][0]
a4=np.where(Y[13]==True)[0][0]

# For each row (i) indexed by A, take only B[i] entries where Y[i]==True.  Assume these indices in X = -1
for i in range(len(A[0])):
    X[A[0][i]][(Y[A][i]==True).nonzero()[0][0:B[i]]]=-1

np.sum(X) # should be -5
X[7,a0]+X[8,a1]+X[8,a2]+X[10,a3]+X[13,a4] # should be -5

如果A是(k,)而不是(1,k),这段代码看起来会更好一些。有任何提高速度的想法吗? - Kevin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接