python - numpy take 无法使用切片进行索引

标签 python arrays numpy slice

根据 take 的 numpy 文档 它与“花式”索引(使用数组索引数组)做同样的事情。但是,如果您需要沿着给定轴的元素,它会更容易使用。

但是,与“花式”或常规 numpy 索引不同,似乎不支持使用切片作为索引:

In [319]: A = np.arange(20).reshape(4, 5)

In [320]: A[..., 1:4]
Out[320]: 
array([[ 1,  2,  3],
       [ 6,  7,  8],
       [11, 12, 13],
       [16, 17, 18]])

In [321]: np.take(A, slice(1, 4), axis=-1)
TypeError: long() argument must be a string or a number, not 'slice'

使用仅在运行时已知的轴上的切片来索引数组的最佳方法是什么?

最佳答案

最有效的方法似乎是 A[(slice(None),) * axis + (slice(1, 4),)]:

In [19]: import numpy as np
    ...: x = np.random.normal(0, 1, (50, 50, 50))
    ...: s = slice(10, 20)
    ...: axis = 2
    ...: 
    ...: 

In [20]: timeit np.rollaxis(np.rollaxis(x, axis, 0)[s], 0, axis + 1)
2.32 µs ± 15.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [21]: timeit x.take(np.arange(x.shape[axis])[s], axis)
28.5 µs ± 38.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [22]: timeit x[(slice(None),) * axis + (s,)]
321 ns ± 0.341 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

关于python - numpy take 无法使用切片进行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28684813/

相关文章:

python - 即时从 python 中的 subprocess.run() 获取输出

python - 使用 Lat-Lon 和时间序列 Pandas 进行操作

python - SQL Server 临时表在 pyodbc 代码中不可用

c# - 为什么我在 C# 编译器中收到此错误 "Unassigned Local Variable"

python - 如何在元组列表中使用 numpy.random.choice?

python - 在 NumPy 中使用 2 个维度进行索引时出错

python - 显示 ico 文件但不显示 jpg/png,{% load staticfiles %} 破坏了代码

python - 如何找到 NumPy 数组中的第一个局部最大值?

php - 如何使多维数组唯一?

python - 如何将数组存储在太大而无法加载到内存中的 hdf5 文件中?