The NumPy package, which comprises the NumPy array as well as many other mathematical functions, has found wide-spread adoption in academia, and industry, including in data science. In the Python world, NumPy arrays are now the standard representation for numerical data.
Basic Usage
To start using Numpy, you must first import the package in your working environment. The code examples below will assume that NumPy is imported as follows:
import numpy as np
To see that it is imported properly, you can check its version as below:
1>>> import numpy as np
2>>> np.__version__
3'1.12.0'
4>>>
5
The NumPy ndarray
One of the key features of NumPy is its N-dimensional array object, or ndarray
. Arrays are similar to lists in Python, except that every element of an array must be of the same type, typically a numeric type like float or int. Arrays make operations with large amounts of numeric data very fast and are generally much more efficient than lists. The array has some important characteristics:
- All elements of an array have the same type.
- Arrays can have multiple dimensions.
- NumPy arrays have a fixed size at creation, unlike Python lists (which can grow dynamically). Changing the size of an
ndarray
will create a new array and delete the original.
Creating NumPy Arrays
Arrays can be created in several ways. For example, we can create an array from a list as shown below:
1import numpy as np
2
3#Create a one-dimensional array from a list
4prices = [12.6, 13.5, 13.2, 14.1, 15.5]
5priceArray = np.array(prices)
6
7#print the array
8print(priceArray)
9
10#You can also check the datatype of the array
11print(priceArray.dtype)
12
Executing the script will print the following to the console:
1C:\pythondatascience>numpyarray.py
2[ 12.6 13.5 13.2 14.1 15.5]
3float64
4
Arrays can be multidimensional. Unlike lists, different axes are accessed using commas inside bracket notation. Here is an example with a two-dimensional array (e.g., a matrix) in Python interactive mode:
1>>> import numpy as np
2>>> a = np.array([[1, 2, 3], [4, 5, 6]], float)
3>>> a
4array([[ 1., 2., 3.],
5 [ 4., 5., 6.]])
6>>> a[0,0]
71.0
8>>> a[1,1]
95.0
10>>>
11
The above array is two-dimensional. We can access the items in the array just like you would with any other Python object using the square brackets and specifying the item index.
Exercise
Create a new list containing the returns you earned on your stock portfolio each day over the past 10 days. Use this list of create an ndarray
. Print the array in the console and share your results in the forum.