这是我的代码:
np.random.seed(0)
luck_A = np.random.uniform(0, 1, 大小 = (2, 1, 100))
A = np.random.uniform(0, 1, 大小 = (2, 1, 100))
index_select_A = (np.argpartition(A, -10)[:, :, -10:])
结果 = np.apply_along_axis(lambda x: lucky_A[x, :, index_select_A[x]], axis=2, arr=luck_A)
我想创建一个数组,其中包含luck_A的元素,但仅包含索引在index_select_A中的元素。但是当我运行代码时,它不断给出错误:用作索引的数组必须是整数(或布尔)类型。但index_select_A中的元素是整数
我已经尝试过 .astype(int)。没成功
您的错误:
Cell In[3], line 9, in <lambda>(x)
5 A = np.random.uniform(0, 1, size = (2, 1, 100))
7 index_select_A = (np.argpartition(A, -10)[:, :, -10:])
----> 9 result = np.apply_along_axis(lambda x: luck_A[x, :, index_select_A[x]], axis=2, arr=luck_A)
IndexError: arrays used as indices must be of integer (or boolean) type
index_select_A[x]
突出显示。
重写 lambda 以允许进行一些打印:
In [4]: def foo(x):
...: print(x)
...: print(index_select_A[x])
...: return luck_A[x, :, index_select_A[x]]
...:
In [5]: np.apply_along_axis(foo, axis=2, arr =luck_A)
[0.5488135 0.71518937 0.60276338 0.54488318 0.4236548 0.64589411
0.43758721 0.891773 0.96366276 0.38344152 0.79172504 0.52889492
0.56804456 0.92559664 0.07103606 0.0871293 0.0202184 0.83261985
...] -------------------------------------------------- ------------------------ IndexError Traceback(最近一次调用最后一次) 第 1 行 [5] 中的单元格 ----> 1 np.apply_along_axis(foo, axis=2, arr =luck_A)
File <__array_function__ internals>:200, in apply_along_axis(*args, **kwargs)
File ~\miniconda3\lib\site-packages\numpy\lib\shape_base.py:379, in apply_along_axis(func1d, axis, arr, *args, **kwargs)
375 except StopIteration as e:
376 raise ValueError(
377 'Cannot apply_along_axis when any iteration dimensions are 0'
378 ) from None
--> 379 res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs))
381 # build a buffer for storing evaluations of func1d.
382 # remove the requested axis, and add the new ones on the end.
383 # laid out so that each write is contiguous.
384 # for a tuple index inds, buff[inds] = func1d(inarr_view[inds])
385 buff = zeros(inarr_view.shape[:-1] + res.shape, res.dtype)
Cell In[4], line 3, in foo(x)
1 def foo(x):
2 print(x)
----> 3 print(index_select_A[x])
4 return luck_A[x, :, index_select_A[x]]
IndexError: arrays used as indices must be of integer (or boolean) type
apply
将 luck_A
的一行形状 (100,) 传递给函数(如 x
)。这是一个浮点数数组。当然不能作为索引!
In [6]: luck_A.shape
Out[6]: (2, 1, 100)