首页 > 解决方案 > 一种在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]])

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

在此先感谢(和之后)

标签: pythonnumpyarray-broadcasting

解决方案


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数组的关键。我就交给你了!


推荐阅读