一种在 numpy 中将一个数组映射到另一个数组的方法?

A way to map one array onto another in numpy?

我有一个二维数组和一个一维数组,如下所示。我想要做的是用二维和一维数组的乘积填充二维数组中的空白区域——可能最简单的演示如下:

all_holdings = np.array([[1, 0, 0, 2, 0],
                         [2, 0, 0, 1, 0]]).astype('float64')
sub_holdings = np.array([0.2, 0.3, 0.5])

我希望得到的结果是:

array([[1. , 0.2, 0.3, 2. , 1. ],
       [2. , 0.4, 0.6, 1. , 0.5]])

即(此处显示的工作原理):

array([[1., 1*0.2, 1*0.3, 2, 2*0.5],
       [2., 2*0.2, 2*0.3, 1, 1*0.5]])

有没有人能想出一种相对快速、最好是矢量化的方法来做到这一点?我必须 运行 在多个二维数组上重复进行此计算,但始终在二维数组的相同位置使用空格。

提前致谢(及之后)

In [76]: all_holdings = np.array([[1, 0, 0, 2, 0], 
    ...:                          [2, 0, 0, 1, 0]]).astype('float64') 
    ...: sub_holdings = np.array([0.2, 0.3, 0.5])                               

一级迭代:

In [77]: idx = np.where(all_holdings[0,:]==0)[0]                                
In [78]: idx                                                                    
Out[78]: array([1, 2, 4])
In [79]: res = all_holdings.copy()                                              
In [80]: for i,j in zip(idx, sub_holdings): 
    ...:     res[:,i] = res[:,i-1]*j 
    ...:                                                                        
In [81]: res                                                                    
Out[81]: 
array([[1.  , 0.2 , 0.06, 2.  , 1.  ],
       [2.  , 0.4 , 0.12, 1.  , 0.5 ]])

糟糕,res[:,2] 列有误;我需要使用 idx-1.

以外的东西

现在我可以更好地想象动作了。例如,所有新值都是:

In [82]: res[:,idx]                                                             
Out[82]: 
array([[0.2 , 0.06, 1.  ],
       [0.4 , 0.12, 0.5 ]])

好的,我需要一种方法将每个 idx 值与正确的非零列正确配对。

In [84]: jdx = np.where(all_holdings[0,:])[0]                                   
In [85]: jdx                                                                    
Out[85]: array([0, 3])

这还不够。

但是让我们假设我们有一个合适的 jdx

In [87]: jdx = np.array([0,0,3])                                                
In [88]: res = all_holdings.copy()                                              
In [89]: for i,j,v in zip(idx,jdx, sub_holdings): 
    ...:     res[:,i] = res[:,j]*v 
    ...:                                                                        
In [90]: res                                                                    
Out[90]: 
array([[1. , 0.2, 0.3, 2. , 1. ],
       [2. , 0.4, 0.6, 1. , 0.5]])
In [91]: res[:,idx]                                                             
Out[91]: 
array([[0.2, 0.3, 1. ],
       [0.4, 0.6, 0.5]])

我在没有迭代的情况下得到了相同的值:

In [92]: all_holdings[:,jdx]*sub_holdings                                       
Out[92]: 
array([[0.2, 0.3, 1. ],
       [0.4, 0.6, 0.5]])

In [94]: res[:,idx] = res[:,jdx] *sub_holdings                                  
In [95]: res                                                                    
Out[95]: 
array([[1. , 0.2, 0.3, 2. , 1. ],
       [2. , 0.4, 0.6, 1. , 0.5]])

所以关键要找到正确的jdx数组。就交给你了!