Reputation: 612
How can I get the type of a multidimensional array?
I treat arrays but considering data type: string
, float
, Boolean
, 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 ...
Upvotes: 22
Views: 54359
Reputation: 970
fruits = [['banana'], [1], [11.12]]
for first_array in range(len(fruits)):
for second_array in range(len(fruits[first_array])):
print('Type :', type(fruits[first_array][second_array]), 'data:', fruits[first_array][second_array])
That show the data type of each values.
Upvotes: 0
Reputation: 394995
Use the dtype
attribute:
>>> import numpy
>>> ar = numpy.array(range(10))
>>> ar.dtype
dtype('int32')
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.dtype
dtype('int32')
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']],
dtype='|S5')
>>> ar = numpy.array([['apple', 'banana'],['c', 'd']])
>>> ar
array([['apple', 'banana'],
['c', 'd']],
dtype='|S6')
>>> ar.dtype
dtype('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
Upvotes: 28