froggy - 1 year ago 74

Python Question

How can I get the type of a multidimensional array?

I treat arrays but considering data type:

`string`

`float`

`Boolean`

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

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

```
>>> 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
```

Source (Stackoverflow)