use*_*913 3 python arrays numpy
numpy中有两个数组.第一个是2d数组,可以将其视为向量列表.第二个是1d数组,可以将其视为2d数组的索引列表.
我想使用1d数组的索引选择2d数组的元素.现在我一直在做
z=rnd.rand(2,10) # a list of 2d vectors of length 10
z_idx=rnd.randint(2,size=z.shape[1]) #indices selecting a dimension of the 2d vector
result=np.array([z[z_idx[i],i] for i in xrange(len(z_idx))])
Run Code Online (Sandbox Code Playgroud)
但这很慢.
在numpy中有更好的方法吗?
可能是最简单的方法:
result = z[z_idx].diagonal()
Run Code Online (Sandbox Code Playgroud)
使用效率可能更高一些arange:
result = z[z_idx, np.arange(z_idx.size)]
Run Code Online (Sandbox Code Playgroud)
更合适但相当于np.indices:
result = z[z_idx, np.indices(z_idx.shape)[0]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1482 次 |
| 最近记录: |