How to get type of multidimensional Numpy array elements in Python
Use the dtype
attribute:
>>> import numpy>>> ar = numpy.array(range(10))>>> ar.dtypedtype('int32')
Explanation
Python lists are like arrays:
>>> [[1, 2], [3, 4]][[1, 2], [3, 4]]
But for analysis and scientific computing, we typically use the numpy package's arrays for high performance calculations:
>>> import numpy as np>>> np.array([[1, 2], [3, 4]])array([[1, 2], [3, 4]])
If you're asking about inspecting the type of the data in the arrays, we can do that by using the index of the item of interest in the array (here I go sequentially deeper until I get to the deepest element):
>>> ar = np.array([[1, 2], [3, 4]])>>> type(ar)<type 'numpy.ndarray'>>>> type(ar[0])<type 'numpy.ndarray'>>>> type(ar[0][0])<type 'numpy.int32'>
We can also directly inspect the datatype by accessing the dtype
attribute
>>> ar.dtypedtype('int32')
If the array is a string, for example, we learn how long the longest string is:
>>> ar = numpy.array([['apple', 'b'],['c', 'd']])>>> ararray([['apple', 'b'], ['c', 'd']], dtype='|S5')>>> ar = numpy.array([['apple', 'banana'],['c', 'd']])>>> ararray([['apple', 'banana'], ['c', 'd']], dtype='|S6')>>> ar.dtypedtype('S6')
I tend not to alias my imports so I have the consistency as seen here, (I usually do import numpy
).
>>> ar.dtype.type<type 'numpy.string_'>>>> ar.dtype.type == numpy.string_True
But it is common to import numpy as np
(that is, alias it):
>>> import numpy as np>>> ar.dtype.type == np.string_True