NumPy, which stands for Numerical Python, is a scientific computing library built on top of the Python programming language.
The most common way to import NumPy into your Python environment is to use the following syntax:
import numpy as np
The import numpy portion of the code tells Python to bring the NumPy library into your current environment.
The as np portion of the code then tells Python to give NumPy the alias of np. This allows you to use NumPy functions by simply typing np.function_name rather than numpy.function_name.
Once you’ve imported NumPy, you can then use the functions built in it to quickly create and analyze data.
How to Create a Basic NumPy Array
The most common data type you’ll work with in NumPy is the array, which can be created by using the np.array() function.
The following code shows how to create a basic one-dimensional NumPy array:
import numpy as np
#define array
x = np.array([1, 12, 14, 9, 5])
#display array
print(x)
[ 1 12 14 9 5]
#display number of elements in array
x.size
5
You can also create multiple arrays and perform operations on them such as addition, subtraction, multiplication, etc.
import numpy as np
#define arrays
x = np.array([1, 12, 14, 9, 5])
y = np.array([2, 3, 3, 4, 2])
#add the two arrays
x+y
array([ 3, 15, 17, 13, 7])
#subtract the two arrays
x-y
array([-1, 9, 11, 5, 3])
#multiply the two arrays
x*y
array([ 2, 36, 42, 36, 10])
Check out the absolute beginner’s guide to NumPy for a detailed introduction to all of the basic NumPy functions.
Potential Errors when Importing NumPy
One potential error you may encounter when importing NumPy is:
NameError: name 'np' is not defined
This occurs when you fail to give NumPy an alias when importing it. Read this tutorial to find out how to quickly fix this error.
Additional Resources
If you’re looking to learn more about NumPy, check out the following resources:
Complete List of Statology Python Guides
Online NumPy documentation page
Official NumPy Twitter page