python - 一种在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
数组的关键。我就交给你了!
推荐阅读
- r - S4 对象是否有类似 lapply 的功能?
- c# - ILoggingBuilder Logging LogLevel in Appsettings Json 似乎没有在 Azure 日志流或 Blob 日志中得到确认
- mysql - 如何在 MySQL 控制台中使用环境变量
- c# - HtmlAgilityPack 未找到应该存在的特定节点
- python - 复制 numpy 数组内容而不更改具有不同 dtype 的数组中的值
- ansible - 有条件地运行 ansible 角色处理程序
- java - 是否可以在 IntelliJ Idea 中使用 init.gradle 脚本?
- c++ - 如何让 Doxygen 不记录我的包含防护?
- r - 根据 `df1` 的一个变量 (`df1$var1`) 在 `df1` 中创建一个变量,以及根据 `df1$var1` 改变的 `df2` 的一个变量
- firebase - Firestore 文档 ID 的有效字符