【问题标题】:Replacing values in numpy array替换numpy数组中的值
【发布时间】:2013-09-11 21:04:44
【问题描述】:

我有两个 numpy 数组,都是 M 乘 N。X 包含随机值。 Y 包含真/假。数组 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

这不起作用。关于修复的任何想法?

【问题讨论】:

    标签: python arrays numpy indexing


    【解决方案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),这段代码看起来会好一些。有什么提高速度的想法吗?
    【解决方案2】:

    不清楚你想做什么,这是我的理解:

    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] 更改为 -1,我只希望替换第一个 y[7][0:2]。如果 B[1] = 3,则更改 y[8][0:3] = -1。
    猜你喜欢
    • 2019-09-26
    • 2012-05-07
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 2014-10-09
    • 2023-03-20
    相关资源
    最近更新 更多