Quick way to access first element in Numpy array with arbitrary number of dimensions?

后端 未结 3 1497
眼角桃花
眼角桃花 2020-12-31 06:51

I have a function that I want to have quickly access the first (aka zeroth) element of a given Numpy array, which itself might have any number of dimensions. What\'s the qu

相关标签:
3条回答
  • 2020-12-31 07:03
    a.flat[0]
    

    This should be pretty fast and never require a copy. (Note that a.flat is an instance of numpy.flatiter, not an array.)

    0 讨论(0)
  • 2020-12-31 07:04

    You can use a.item(0); see the documentation at numpy.ndarray.item.

    A possible disadvantage of this approach is that the return value is a Python data type, not a numpy object. For example, if a has data type numpy.uint8, a.item(0) will be a Python integer. If that is a problem, a.flat[0] is better--see @user2357112's answer.

    0 讨论(0)
  • 2020-12-31 07:16
    ## y -- numpy array of shape (1, Ty)
    

    if you want to get the first element:

    use y.shape[0]

    if you want to get the second element:

    use y.shape[1]

    Source: https://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html

    You can also use the take for more complicated extraction (to get few elements):

    numpy.take(a, indices, axis=None, out=None, mode='raise')[source] Take elements from an array along an axis.

    0 讨论(0)
提交回复
热议问题