简体   繁体   English

对矩阵运算的精美索引

[英]Fancy indexing to matrix operations

Suppose:认为:

A=np.array([1,2,0,-4])

B=np.array([1,1,1,1])

C=np.array([1,2,3,4])

With fancy indexing I can assign a scalar value to C wherever A > 0.通过花哨的索引,我可以在 A > 0 的地方为 C 分配一个标量值。

C[A > 0]= 1

But is there anyway to get something like C = B/A wherever A > 0 while preserving the original values of C for A <= 0 with fancy indexing?但无论如何,在 A > 0 的情况下,在保留 A <= 0 的 C 的原始值的情况下,是否可以通过花哨的索引获得类似 C = B/A 的东西? If I try something like如果我尝试类似

C[A > 0] =  B/A  

I get an error like:我收到如下错误:

<input>:1: RuntimeWarning: divide by zero encountered in true_divide
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: NumPy boolean array indexing assignment cannot assign 4 input values to the 2      output values where the mask is true

I can get the result with a for loop or making copies of A & C where:我可以通过 for 循环或复制 A & C 来获得结果,其中:

D = np.copy(A)
E = np.copy(C) 
D[ D <= 0]= 1
E=B/A
E[A <=0] = C 
 

or set C=Run(A,B) where或设置 C=Run(A,B) 其中

def Run(A,B):
    C=np.zeros(A.shape[0],A.shape[1])
    for i in range(len(A)):
        if A[i] != O: 
            C[i] = A[i]/B[i]
        else:
            C[i] = C[i]       

But i was just wondering if there was a more direct way to do it without adding so many steps if i am looping millions of times.但我只是想知道如果我循环数百万次,是否有更直接的方法可以做到这一点而无需添加这么多步骤。 Thanks.谢谢。

You can index the operands: C[A > 0] = B[A > 0] / A[A > 0] .您可以索引操作数: C[A > 0] = B[A > 0] / A[A > 0] You might want to compute A > 0 once, and reuse it, eg您可能想计算A > 0一次,然后重用它,例如

mask = A > 0
C[mask] =  B[mask] / A[mask]

A more efficient alternative is to use the where parameter of np.divide or np.floor_divide .更有效的替代方法是使用np.dividenp.floor_dividewhere参数。 For example,例如,

In [19]: A = np.array([1, 2, 0, -4])                                            

In [20]: B = np.array([1, 1, 1, 1])

In [21]: C = np.array([1, 2, 3, 4])

In [22]: np.floor_divide(B, A, where=A > 0, out=C)
Out[22]: array([1, 0, 3, 4])

In [23]: C        
Out[23]: array([1, 0, 3, 4])

I had to use floor_divide because all the arrays are integer arrays, and numpy.divide creates a floating point array, so that function will complain about the type mismatch if the out array is an integer array. I had to use floor_divide because all the arrays are integer arrays, and numpy.divide creates a floating point array, so that function will complain about the type mismatch if the out array is an integer array. If you want a floating point result, C should be an array of floating point values:如果你想要一个浮点结果, C应该是一个浮点值数组:

In [24]: C = np.array([1., 2., 3., 4.])

In [25]: np.divide(B, A, where=A > 0, out=C)
Out[25]: array([1. , 0.5, 3. , 4. ])

In [26]: C
Out[26]: array([1. , 0.5, 3. , 4. ])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM