【问题标题】:Fancy indexing to matrix operations对矩阵运算的精美索引
【发布时间】:2020-12-06 21:55:01
【问题描述】:

假设:

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

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

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

通过精美的索引,我可以在 A > 0 的地方为 C 分配一个标量值。

C[A > 0]= 1

但是无论如何在 A > 0 的地方获得像 C = B/A 这样的东西,同时通过花哨的索引保留 A

C[A > 0] =  B/A  

我收到如下错误:

<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

我可以通过 for 循环或复制 A & C where 来获得结果:

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

或在哪里设置 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]       

但我只是想知道如果我循环数百万次,是否有更直接的方法来做到这一点而无需添加这么多步骤。谢谢。

【问题讨论】:

    标签: python numpy indexing numpy-ndarray


    【解决方案1】:

    您可以索引操作数:C[A &gt; 0] = B[A &gt; 0] / A[A &gt; 0]。您可能想计算一次A &gt; 0,然后重复使用它,例如

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

    更有效的替代方法是使用np.dividenp.floor_dividewhere 参数。例如,

    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])
    

    我不得不使用floor_divide,因为所有数组都是整数数组,而numpy.divide 创建了一个浮点数组,因此如果out 数组是整数数组,该函数将抱怨类型不匹配。如果你想要一个浮点结果,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. ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2019-10-04
      • 2022-01-14
      • 1970-01-01
      • 2012-11-06
      相关资源
      最近更新 更多