简体   繁体   English

如何从numpy中的1维数组中提取零维切片

[英]how to extract a zero-dimensional slice from a 1-dimensional array in numpy

Is there a way to slice a zero-dimensional sub-array from a 1-dimensional array? 有没有办法从一维数组切割零维子阵列?

For example, if I have a N-dimensional ndarray arr , arr[0] returns a (N-1)-dimensional ndarray . 例如,如果我有一个N维的ndarray arrarr[0]返回一个(N-1)维的ndarray

However, if I have a 1-dimensional ndarray x , x[0] doesn't return a 0-dimensional ndarray, but rather a numpy.int64 , (if x contains int64 s). 但是,如果我有一维ndarray xx[0]不返回0维ndarray,而是返回numpy.int64 ,(如果x包含int64 s)。

Minimal example: 最小的例子:

def increment(zero_d_array):
    zero_d_array[...] = zero_d_array + 1

counter = numpy.array(0)  # a zero-dimensional array containing scalar 0
increment(counter)        # success; counter is now 1

counters = numpy.zeros(3, dtype=int)  # [0, 0, 0]
increment(counter[1])    # fails; counter[1] is a numpy.int64, not a 0-D array

I realize the above would work with increment(counter[1:2]) , but only because increment() happens to work with both 0-D and 1-D inputs. 我意识到上面的方法可以用increment(counter[1:2]) ,但只是因为increment()恰好适用于0-D和1-D输入。 Not all functions will be so flexible. 并非所有功能都会如此灵活。

使用省略号:

increment(counter[1, ...])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM