ndarray - Methods and Data Type

Once you have created an array, you can check its various attributes using the inbuilt functions. Some of these are described below:

ndarray.ndim

Returns the number of array dimensions.

>>> a
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])
>>> a.ndim
2
>>> x = np.array([1, 2, 3])
>>> x.ndim
1

ndarray.shape

Returns a tuple of array dimensions. It can also be used to "reshape" the array, as long as this would not require a change in the total number of elements.

>>> a.shape
(2, 3)
>>> x.shape
(3,)
>>> a.shape = (3,2)
>>> a
array([[ 1.,  2.],
       [ 3.,  4.],
       [ 5.,  6.]])

ndarray.size

Returns the number of elements in the array. This can also be calculated with np.prod(a.shape), i.e., the product of the array’s dimensions.

>>> a
array([[ 1.,  2.],
       [ 3.,  4.],
       [ 5.,  6.]])
>>> a.size
6
>>> np.prod(a.shape)
6

NumPy array: default types

NumPy types are typically numeric types such as integers and floats of different precisions.

>>> import numpy as np
>>> qty = np.array([5,7,4,10,16])
>>> qty.dtype
dtype('int32')
>>> price = np.array([5,8,12.7,89.6,12.9,5.4])
>>> price.dtype
dtype('float64')
>>>

There are also some other types:

NumPy typeExample
Intmyarr = np.array( [1, 5, 0, 3 ] )
Floatmyarr = np.array( [1, 5, 0, 3.1] )
Complexmyarr = np.array( [1+2j, 3+4j, 6+7j] )
Boolmyarr = np.array( [True, False, True] )
Stringmyarr = np.array( ['Jon', 'Georg', 'Jose'] )

Casting Array Data Types

An array with one dtype can be converted or casted into another dtype using ndarray’s astype method.

>>> import numpy as np
>>> qty = np.array([5,7,4,10,16])
>>> qty.dtype
dtype('int32')
>>> float_qty = qty.astype(np.float64)
>>> float_qty.dtype
dtype('float64')
>>>

Casting can be specifically useful if you have an array of strings representing numeric data (numbers in quotes).

>>> prices = np.array(['5.1','8.6','12.7','89.6','12.9','5.4'])
>>> prices
array(['5.1', '8.6', '12.7', '89.6', '12.9', '5.4'],
      dtype='<U4')
>>> prices_num = prices.astype(float)
>>> prices_num
array([  5.1,   8.6,  12.7,  89.6,  12.9,   5.4])
>>> prices_num.dtype
dtype('float64')
>>>