ndarray - Methods and Data Type

Premium

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.

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

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.

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

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.

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

NumPy array: default types

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

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

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.

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

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

1>>> prices = np.array(['5.1','8.6','12.7','89.6','12.9','5.4'])
2>>> prices
3array(['5.1', '8.6', '12.7', '89.6', '12.9', '5.4'],
4      dtype='<U4')
5>>> prices_num = prices.astype(float)
6>>> prices_num
7array([  5.1,   8.6,  12.7,  89.6,  12.9,   5.4])
8>>> prices_num.dtype
9dtype('float64')
10>>>
11