Gar*_*erg 0 python arrays indexing numpy
我有一个2D数组值和一个索引数组.我想使用索引数组从每行的索引中提取值.以下代码将成功执行此操作:
from pprint import pprint
import numpy as np
_2Darray = np.arange(100, dtype = np.float16)
_2Darray = _2Darray.reshape((10, 10))
array_indexes = [5,5,5,4,4,4,6,6,6,8]
index_values = []
for row, index in enumerate(array_indexes):
index_values.append(_2Darray[row, index])
pprint(_2Darray)
print index_values
Run Code Online (Sandbox Code Playgroud)
返回
array([[ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[ 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.],
[ 20., 21., 22., 23., 24., 25., 26., 27., 28., 29.],
[ 30., 31., 32., 33., 34., 35., 36., 37., 38., 39.],
[ 40., 41., 42., 43., 44., 45., 46., 47., 48., 49.],
[ 50., 51., 52., 53., 54., 55., 56., 57., 58., 59.],
[ 60., 61., 62., 63., 64., 65., 66., 67., 68., 69.],
[ 70., 71., 72., 73., 74., 75., 76., 77., 78., 79.],
[ 80., 81., 82., 83., 84., 85., 86., 87., 88., 89.],
[ 90., 91., 92., 93., 94., 95., 96., 97., 98., 99.]], dtype=float16)
[5.0, 15.0, 25.0, 34.0, 44.0, 54.0, 66.0, 76.0, 86.0, 98.0]
Run Code Online (Sandbox Code Playgroud)
但我想只用numpy函数来做.我已经尝试了一大堆numpy函数,但它们似乎都没有完成这个相当简单的任务.
提前致谢!
编辑 我设法弄清楚我的实现是什么:V_high = np.fromiter((
index_values = _2Darray[ind[0], ind[1]] for ind in
enumerate(array_indexes)),
dtype = _2Darray.dtype,
count = len(_2Darray))
Run Code Online (Sandbox Code Playgroud)
感谢root,我已经完成了两个实现.现在进行一些分析:我的实现通过cProfiler运行
ncalls tottime percall cumtime percall filename:lineno(function)
2 0.274 0.137 0.622 0.311 {numpy.core.multiarray.fromiter}
20274 0.259 0.000 0.259 0.000 lazer_np.py:86(<genexpr>)
Run Code Online (Sandbox Code Playgroud)
和root的:
4 0.000 0.000 0.000 0.000 {numpy.core.multiarray.array}
1 0.000 0.000 0.000 0.000 {numpy.core.multiarray.arange}
Run Code Online (Sandbox Code Playgroud)
我简直不敢相信,但是cProfiler并没有检测到root的方法.我认为这肯定是某种错误,但它肯定明显更快.在早期的测试中,我获得了大约3倍的速度
注意:这些测试是在np.float16值的shape =(20273,200)数组上完成的.此外,每个测试必须运行两次索引.
这应该这样做:
row = numpy.arange(_2Darray.shape[0])
index_values = _2Darray[row, array_indexes]
Run Code Online (Sandbox Code Playgroud)
Numpy允许您使用两个数组索引2d数组(或者确实是nd数组),这样:
for i in range(len(row)):
result1[i] = array[row[i], col[i]]
result2 = array[row, col]
numpy.all(result1 == result2)
Run Code Online (Sandbox Code Playgroud)