- Python Dictionaries
- Comparison Operators in Python
- Logical Operators in Python
- Conditional Statements in Python
- For Loop in Python
- While Loop in Python
- How to loop over python dictionaries and Numpy arrays
- What is NumPy in Python
- ndarray - Methods and Data Type
- NumPy - Methods to Create Arrays
- Python NumPy - Numerical Operations on Arrays
- Python NumPy - Indexing and Slicing Arrays
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:
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
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.]])
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:
Casting Array Data Types
An array with one dtype can be converted or casted into another dtype using ndarray’s
>>> 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') >>>