我有两个numpy数组,两个M都是N.X包含随机值。 Y包含true / false。数组A包含X中需要替换的行的索引,值为-1。我想只替换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个。
B = [1,2,1,1]
然后对于每个索引i(循环中),
X[i][Y[A][i]==True][0:B[i]] = -1
这不起作用。关于修复的任何想法?
答案 0 :(得分: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
答案 1 :(得分: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