Python numpy.matrix matrix index method (item)

First, the environment:

numpy 1.16.4
python 3.7

Second, the description:

import numpy as np
a = np.mat([[1]])
print(type(a))
print("a:",a)
print("a[0][0]:",a[0][0])

Output:
Here Insert Picture Description
It can be seen directly in the index can not be indexed numpy.matrixl target

If numpy.ndarray type, it can be indexed

import numpy as np
a = np.array([[1.]])
print(type(a))
print("a:",a)
print("a[0][0]:",a[0][0])

Here Insert Picture Description

Personal Analysis: Type matrixl when [[1]] is a (1,1) matrix objects, direct index [0] [0] is essentially the object matrix index, so the same result
is when the array index elements within the array

Third, resolve:

import numpy as np
a = np.mat([[1.]])
print(type(a))
print("a:",a)
print("a[0][0]:",a[0][0])
print("item方法:",a.item(0,0))

Here Insert Picture Description

Four, item Detailed methods (lists and matrices can be used in this method):

a.item (* args)
copies the elements of the array to a scalar standard Python and returns it.
Parameter (variable type and number)

  • none: In this case, the array method is only valid for
    only one element ( 'a.size == 1'), which element is
    copied to standard Python scalar object and returns.
  • int_type: this parameter is interpreted as a plane index
    array, which specify copy and return elements.
  • int_types tuples: single int_type same function parameter,
    the parameter is interpreted as an index nd
    array.

return value:

  • z: Python scalar standard object
    a copy of the specified element of the array
    Python scalars

When 'a' data type is longdouble or clongdouble, item () you return a scalar array object, because scalar Python is not available, no information is lost. Void array returned as item () a buffer object, unless defined fields, otherwise it will return a tuple.
'Item' and [args] is very similar, except that it is not a scalar array and returns a scalar standard Python. This operation is performed for elements and access elements of the array is useful for accelerating, optimizing the use of mathematical array Python.

example:

            >>> np.random.seed(123)
            >>> x = np.random.randint(9, size=(3, 3))
            >>> x
            array([[2, 2, 6],
                   [1, 3, 6],
                   [1, 0, 1]])
            >>> x.item(3)
            1
            >>> x.item(7)
            0
            >>> x.item((0, 1))
            2
            >>> x.item((2, 2))
            1

Finally, thanks pottery teacher's instructions!

Published 45 original articles · won praise 28 · views 10000 +

Guess you like

Origin blog.csdn.net/m0_43505377/article/details/103926463