froggy froggy - 1 year ago 127
Python Question

How to get type of multidimensional Numpy array elements in Python

How can I get the type of a multidimensional array?

I treat arrays but considering data type:

, I have to adapt code so I would have to get the type regardless of dimension that can be one two dimensions or more.

Data can be 1d of real, 3D of string ...

I would like to recover type of Array, is it a real , is it a string is it a boolean ...
without doing Array[0] or Array [0][0][0][0] because dimension can be various.
Or a way to get the first element of an array whatever the dimensions.

It works with np.isreal a bit modified , but I don't found equivalent like isastring or isaboolean ...

Answer Source

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:

>>> 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.dtype

If the array is a string, for example, we learn how long the longest string is:

>>> ar = numpy.array([['apple', 'b'],['c', 'd']])
>>> ar
array([['apple', 'b'],
       ['c', 'd']], 
>>> ar = numpy.array([['apple', 'banana'],['c', 'd']])
>>> ar
array([['apple', 'banana'],
       ['c', 'd']], 
>>> ar.dtype

I tend not to alias my imports.

>>> ar.dtype.type
<type 'numpy.string_'>
>>> ar.dtype.type == numpy.string_

But it is common to import numpy as np (that is, alias it):

>>> import numpy as np
>>> ar.dtype.type == np.string_
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download