NumPy - The Absolute Basics For Beginners - NumPy v1.23 Manual
NumPy - The Absolute Basics For Beginners - NumPy v1.23 Manual
Welcome to NumPy!
NumPy (Numerical Python) is an open source Python library that’s used in
almost every field of
science and engineering. It’s the universal standard for
working with numerical data in Python, and it’s
at the core of the scientific
Python and PyData ecosystems. NumPy users include everyone from
beginning coders
to experienced researchers doing state-of-the-art scientific and industrial
research
and development. The NumPy API is used extensively in Pandas, SciPy,
Matplotlib, scikit-learn, scikit-
image and most other data science and
scientific Python packages.
The NumPy library contains multidimensional array and matrix data structures
(you’ll find more
information about this in later sections). It provides
ndarray, a homogeneous n-dimensional array
object, with methods to
efficiently operate on it. NumPy can be used to perform a wide variety of
mathematical operations on arrays. It adds powerful data structures to Python
that guarantee efficient
calculations with arrays and matrices and it supplies
an enormous library of high-level mathematical
functions that operate on these
arrays and matrices.
Installing NumPy
To install NumPy, we strongly recommend using a scientific Python distribution.
If you’re looking for
the full instructions for installing NumPy on your
operating system, see Installing NumPy.
or
If you don’t have Python yet, you might want to consider using Anaconda. It’s the easiest way to get
started. The good
thing about getting this distribution is the fact that you don’t need to worry
too
much about separately installing NumPy or any of the major packages that
you’ll be using for your
data analyses, like pandas, Scikit-Learn, etc.
import numpy as np
>>> a = np.arange(6)
>>> a2 = a[np.newaxis, :]
>>> a2.shape
(1, 6)
If you aren’t familiar with this style, it’s very easy to understand.
If you see >>>, you’re looking at input,
or the code that
you would enter. Everything that doesn’t have >>> in front of it
is output, or the
results of running your code. This is the style
you see when you run python on the command line, but
if you’re using
IPython, you might see a different style. Note that it is not part of the
code and will
cause an error if typed or pasted into the Python
shell. It can be safely typed or pasted into the
IPython shell; the >>>
is ignored.
NumPy arrays are faster and more compact than Python lists. An array consumes
less memory and is
convenient to use. NumPy uses much less memory to store data
and it provides a mechanism of
specifying the data types. This allows the code
to be optimized even further.
What is an array?
An array is a central data structure of the NumPy library. An array is a grid of
values and it contains
information about the raw data, how to locate an element,
and how to interpret an element. It has a
grid of elements that can be indexed
in various ways.
The elements are all of the same type, referred
to as the array dtype.
One way we can initialize NumPy arrays is from Python lists, using nested lists
for two- or higher-
dimensional data.
For example:
or:
We can access the elements in the array using square brackets. When you’re
accessing elements,
remember that indexing in NumPy starts at 0. That means that
if you want to access the first element
in your array, you’ll be accessing
element “0”.
>>> print(a[0])
[1 2 3 4]
An array is usually a fixed-size container of items of the same type and size.
The number of
dimensions and items in an array is defined by its shape. The
shape of an array is a tuple of non-
negative integers that specify the sizes of
each dimension.
In NumPy, dimensions are called axes. This means that if you have a 2D array
that looks like this:
Your array has 2 axes. The first axis has a length of 2 and the second axis has
a length of 3.
Just like in other Python container objects, the contents of an array can be
accessed and modified by
indexing or slicing the array. Unlike the typical container
objects, different arrays can share the same
data, so changes made on one array might
be visible in another.
All you need to do to create a simple array is pass a list to it. If you choose
to, you can also specify the
Search the docs ... type of data in your list.
You can find more information about data types here.
What is NumPy?
>>> a = np.array([1, 2, 3])
Installation
NumPy quickstart You can visualize your array this way:
NumPy: the absolute basics for
beginners
NumPy fundamentals
Miscellaneous
NumPy for MATLAB users
Building from source
Using NumPy C-API Be aware that these visualizations are meant to simplify ideas and give you a basic understanding of NumPy
NumPy Tutorials
concepts and mechanics. Arrays and array operations are much more complicated than are captured here!
NumPy How Tos
Besides creating an array from a sequence of elements, you can easily create an
array filled with 0’s:
For downstream package authors
F2PY user guide and reference
manual
manual
Glossary >>> np.zeros(2)
array([0., 0.])
Under-the-hood Documentation
for developers
Or an array filled with 1’s:
Reporting bugs
Release notes >>> np.ones(2)
Or even an empty array! The function empty creates an array whose initial
content is random and
depends on the state of the memory. The reason to use
empty over zeros (or something similar) is
speed - just make sure to
fill every element afterwards!
>>> np.empty(2)
>>> np.arange(4)
array([0, 1, 2, 3])
And even an array that contains a range of evenly spaced intervals. To do this,
you will specify the first
number, last number, and the step size.
>>> np.arange(2, 9, 2)
array([2, 4, 6, 8])
You can also use np.linspace() to create an array with values that are
spaced linearly in a specified
interval:
While the default data type is floating point (np.float64), you can explicitly
specify which data type
you want using the dtype keyword.
>>> x
array([1, 1])
Sorting an element is simple with np.sort(). You can specify the axis, kind,
and order when you call
the function.
>>> np.sort(arr)
array([1, 2, 3, 4, 5, 6, 7, 8])
In addition to sort, which returns a sorted copy of an array, you can use:
array([1, 2, 3, 4, 5, 6, 7, 8])
array([[1, 2],
[3, 4],
[5, 6]])
In order to remove elements from an array, it’s simple to use indexing to select
the elements that you
want to keep.
ndarray.ndim will tell you the number of axes, or dimensions, of the array.
ndarray.size will tell you the total number of elements of the array. This
is the product of the
elements of the array’s shape.
...
...
>>> array_example.size
24
>>> array_example.shape
(3, 2, 4)
Yes!
Using arr.reshape() will give a new shape to an array without changing the
data. Just remember that
when you use the reshape method, the array you want to
produce needs to have the same number of
elements as the original array. If you
start with an array with 12 elements, you’ll need to make sure
that your new
array also has a total of 12 elements.
>>> a = np.arange(6)
>>> print(a)
[0 1 2 3 4 5]
You can use reshape() to reshape your array. For example, you can reshape
this array to an array
with three rows and two columns:
>>> b = a.reshape(3, 2)
>>> print(b)
[[0 1]
[2 3]
[4 5]]
array([[0, 1, 2, 3, 4, 5]])
newshape is the new shape you want. You can specify an integer or a tuple of
integers. If you specify an
integer, the result will be an array of that length.
The shape should be compatible with the original
shape.
If you want to learn more about C and Fortran order, you can
read more about the internal
organization of NumPy arrays here.
Essentially, C and Fortran orders have to do with how indices
correspond
to the order the array is stored in memory. In Fortran, when moving through
the elements
of a two-dimensional array as it is stored in memory, the first
index is the most rapidly varying index.
As the first index moves to the next
row as it changes, the matrix is stored one column at a time.
This
is why Fortran is thought of as a Column-major language.
In C on the other hand, the last index
changes
the most rapidly. The matrix is stored by rows, making it a Row-major
language. What you do
for C or Fortran depends on whether it’s more important
to preserve the indexing convention or not
reorder the data.
Using np.newaxis will increase the dimensions of your array by one dimension
when used once. This
means that a 1D array will become a 2D array, a
2D array will become a 3D array, and so on.
>>> a.shape
(6,)
>>> a2 = a[np.newaxis, :]
>>> a2.shape
(1, 6)
You can explicitly convert a 1D array with either a row vector or a column
vector using np.newaxis. For
example, you can convert a 1D array to a row
vector by inserting an axis along the first dimension:
>>> row_vector.shape
(1, 6)
Or, for a column vector, you can insert an axis along the second dimension:
>>> col_vector.shape
(6, 1)
You can also expand an array by inserting a new axis at a specified position
with np.expand_dims.
>>> a.shape
(6,)
>>> b.shape
(6, 1)
>>> c.shape
(1, 6)
>>> data[1]
>>> data[0:2]
array([1, 2])
>>> data[1:]
array([2, 3])
>>> data[-2:]
array([2, 3])
You may want to take a section of your array or specific array elements to use
in further analysis or
additional operations. To do that, you’ll need to subset,
slice, and/or index your arrays.
If you want to select values from your array that fulfill certain conditions,
it’s straightforward with
NumPy.
You can easily print all of the values in the array that are less than 5.
[1 2 3 4]
You can also select, for example, numbers that are equal to or greater than 5,
and use that condition
to index an array.
>>> print(a[five_up])
[ 5 6 7 8 9 10 11 12]
>>> print(divisible_by_2)
[ 2 4 6 8 10 12]
Or you can select elements that satisfy two conditions using the & and |
operators:
>>> c = a[(a > 2) & (a < 11)]
>>> print(c)
[ 3 4 5 6 7 8 9 10]
You can also make use of the logical operators & and | in order to
return boolean values that specify
whether or not the values in an array fulfill
a certain condition. This can be useful with arrays that
contain names or other
categorical values.
>>> print(five_up)
You can also use np.nonzero() to select elements or indices from an array.
You can use np.nonzero() to print the indices of elements that are, for
example, less than 5:
>>> print(b)
In this example, a tuple of arrays was returned: one for each dimension. The
first array represents the
row indices where these values are found, and the
second array represents the column indices where
the values are found.
If you want to generate a list of coordinates where the elements exist, you can
zip the arrays, iterate
over the list of coordinates, and print them. For
example:
... print(coord)
(0, 0)
(0, 1)
(0, 2)
(0, 3)
You can also use np.nonzero() to print the elements in an array that are less
than 5 with:
>>> print(a[b])
[1 2 3 4]
If the element you’re looking for doesn’t exist in the array, then the returned
array of indices will be
empty. For example:
>>> print(not_there)
You can easily create a new array from a section of an existing array.
You can create a new array from a section of your array any time by specifying
where you want to slice
your array.
>>> arr1
array([4, 5, 6, 7, 8])
Here, you grabbed a section of your array from index position 3 through index
position 8.
You can also stack two existing arrays, both vertically and horizontally. Let’s
say you have two arrays,
a1 and a2:
array([[1, 1],
[2, 2],
[3, 3],
[4, 4]])
array([[1, 1, 3, 3],
[2, 2, 4, 4]])
You can split an array into several smaller arrays using hsplit. You can
specify either the number of
equally shaped arrays to return or the columns
after which the division should occur.
>>> x
[13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]])
If you wanted to split this array into three equally shaped arrays, you would
run:
>>> np.hsplit(x, 3)
[array([[ 1, 2, 3, 4],
If you wanted to split your array after the third and fourth column, you’d run:
>>> np.hsplit(x, (3, 4))
[array([[ 1, 2, 3],
You can use the view method to create a new array object that looks at the
same data as the original
array (a shallow copy).
>>> b1 = a[0, :]
>>> b1
array([1, 2, 3, 4])
>>> b1[0] = 99
>>> b1
array([99, 2, 3, 4])
>>> a
array([[99, 2, 3, 4],
[ 5, 6, 7, 8],
Using the copy method will make a complete copy of the array and its data (a
deep copy). To use this
on your array, you could run:
>>> b2 = a.copy()
Once you’ve created your arrays, you can start to work with them. Let’s say,
for example, that you’ve
created two arrays, one called “data” and one called
“ones”
You can add the arrays together with the plus sign.
array([2, 3])
array([0, 1])
array([1, 4])
array([1., 1.])
Basic operations are simple with NumPy. If you want to find the sum of the
elements in an array, you’d
use sum(). This works for 1D arrays, 2D arrays,
and arrays in higher dimensions.
>>> a.sum()
10
To add the rows or the columns in a 2D array, you would specify the axis.
>>> b.sum(axis=0)
array([3, 3])
>>> b.sum(axis=1)
array([2, 4])
Broadcasting
There are times when you might want to carry out an operation between an array
and a single number
(also called an operation between a vector and a scalar)
or between arrays of two different sizes. For
example, your array (we’ll call it
“data”) might contain information about distance in miles but you want
to
convert the information to kilometers. You can perform this operation with:
array([1.6, 3.2])
NumPy understands that the multiplication should happen with each cell. That
concept is called
broadcasting. Broadcasting is a mechanism that allows
NumPy to perform operations on arrays of
different shapes. The dimensions of
your array must be compatible, for example, when the
dimensions of both arrays
are equal or when one of them is 1. If the dimensions are not compatible,
you
will get a ValueError.
>>> data.max()
2.0
>>> data.min()
1.0
>>> data.sum()
3.0
It’s very common to want to aggregate along a row or column. By default, every
NumPy aggregation
function will return the aggregate of the entire array. To
find the sum or the minimum of the elements
in your array, run:
>>> a.sum()
4.8595784
Or:
>>> a.min()
0.05093587
You can specify on which axis you want the aggregation function to be computed.
For example, you
can find the minimum value within each column by specifying
axis=0.
>>> a.min(axis=0)
The four values listed above correspond to the number of columns in your array.
With a four-column
array, you will get four values as your result.
Creating matrices
You can pass Python lists of lists to create a 2-D array (or “matrix”) to
represent them in NumPy.
>>> data
array([[1, 2],
[3, 4],
[5, 6]])
Indexing and slicing operations are useful when you’re manipulating matrices:
>>> data[0, 1]
>>> data[1:3]
array([[3, 4],
[5, 6]])
>>> data[0:2, 0]
array([1, 3])
You can aggregate matrices the same way you aggregated vectors:
>>> data.max()
>>> data.min()
>>> data.sum()
21
You can aggregate all the values in a matrix and you can aggregate them across
columns or rows using
the axis parameter. To illustrate this point, let’s
look at a slightly modified dataset:
>>> data = np.array([[1, 2], [5, 3], [4, 6]])
>>> data
array([[1, 2],
[5, 3],
[4, 6]])
>>> data.max(axis=0)
array([5, 6])
>>> data.max(axis=1)
array([2, 5, 6])
Once you’ve created your matrices, you can add and multiply them using
arithmetic operators if you
have two matrices that are the same size.
array([[2, 3],
[4, 5]])
You can do these arithmetic operations on matrices of different sizes, but only
if one matrix has only
one column or one row. In this case, NumPy will use its
broadcast rules for the operation.
array([[2, 3],
[4, 5],
[6, 7]])
Be aware that when NumPy prints N-dimensional arrays, the last axis is looped
over the fastest while
the first axis is the slowest. For instance:
>>> np.ones((4, 3, 2))
array([[[1., 1.],
[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.],
[1., 1.]]])
There are often instances where we want NumPy to initialize the values of an
array. NumPy offers
functions like ones() and zeros(), and the
random.Generator class for random number generation
for that.
All you need to do is pass in the number of elements you want it to generate:
>>> np.ones(3)
>>> np.zeros(3)
>>> rng.random(3)
array([[1., 1.],
[1., 1.],
[1., 1.]])
array([[0., 0.],
[0., 0.],
[0., 0.]])
array([[0.01652764, 0.81327024],
[0.91275558, 0.60663578],
Read more about creating arrays, filled with 0’s, 1’s, other values or
uninitialized, at array creation
routines.
With Generator.integers, you can generate random integers from low (remember
that this is
inclusive with NumPy) to high (exclusive). You can set
endpoint=True to make the high number
inclusive.
array([[2, 1, 1, 0],
You can find the unique elements in an array easily with np.unique.
>>> a = np.array([11, 11, 12, 13, 14, 15, 16, 17, 12, 13, 11, 14, 18, 19, 20])
you can use np.unique to print the unique values in your array:
>>> print(unique_values)
[11 12 13 14 15 16 17 18 19 20]
To get the indices of unique values in a NumPy array (an array of first index
positions of unique values
in the array), just pass the return_index
argument in np.unique() as well as your array.
>>> print(indices_list)
[ 0 2 3 4 5 6 7 12 13 14]
You can pass the return_counts argument in np.unique() along with your
array to get the frequency
count of unique values in a NumPy array.
>>> print(occurrence_count)
[3 2 2 2 1 1 1 1 1 1]
>>> a_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [1, 2, 3, 4]])
>>> print(unique_values)
[ 1 2 3 4 5 6 7 8 9 10 11 12]
If you want to get the unique rows or columns, make sure to pass the axis
argument. To find the
unique rows, specify axis=0 and for columns, specify
axis=1.
>>> print(unique_rows)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
To get the unique rows, index position, and occurrence count, you can use:
>>> print(unique_rows)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
>>> print(indices)
[0 1 2]
>>> print(occurrence_count)
[2 1 1]
To learn more about finding the unique elements in an array, see unique.
It’s common to need to transpose your matrices. NumPy arrays have the property
T that allows you to
transpose a matrix.
You may also need to switch the dimensions of a matrix. This can happen when,
for example, you have
a model that expects a certain input shape that is
different from your dataset. This is where the
reshape method can be useful.
You simply need to pass in the new dimensions that you want for the
matrix.
>>> data.reshape(2, 3)
array([[1, 2, 3],
[4, 5, 6]])
>>> data.reshape(3, 2)
array([[1, 2],
[3, 4],
[5, 6]])
You can also use .transpose() to reverse or change the axes of an array
according to the values you
specify.
>>> arr
array([[0, 1, 2],
[3, 4, 5]])
>>> arr.transpose()
array([[0, 3],
[1, 4],
[2, 5]])
>>> arr.T
array([[0, 3],
[1, 4],
[2, 5]])
To learn more about transposing and reshaping arrays, see transpose and
reshape.
Reversing a 1D array
Reversed Array: [8 7 6 5 4 3 2 1]
Reversing a 2D array
>>> arr_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
You can reverse the content in all of the rows and all of the columns with:
>>> print(reversed_arr)
[[12 11 10 9]
[ 8 7 6 5]
[ 4 3 2 1]]
>>> print(reversed_arr_rows)
[[ 9 10 11 12]
[ 5 6 7 8]
[ 1 2 3 4]]
>>> print(reversed_arr_columns)
[[ 4 3 2 1]
[ 8 7 6 5]
[12 11 10 9]]
You can also reverse the contents of only one column or row. For example, you
can reverse the
contents of the row at index position 1 (the second row):
>>> print(arr_2d)
[[ 1 2 3 4]
[ 8 7 6 5]
[ 9 10 11 12]]
You can also reverse the column at index position 1 (the second column):
>>> print(arr_2d)
[[ 1 10 3 4]
[ 8 7 6 5]
[ 9 2 11 12]]
There are two popular ways to flatten an array: .flatten() and .ravel().
The primary difference
between the two is that the new array created using
ravel() is actually a reference to the parent array
(i.e., a “view”). This
means that any changes to the new array will affect the parent array as well.
Since
ravel does not create a copy, it’s memory efficient.
>>> x.flatten()
When you use flatten, changes to your new array won’t change the parent
array.
For example:
>>> a1 = x.flatten()
>>> a1[0] = 99
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[99 2 3 4 5 6 7 8 9 10 11 12]
But when you use ravel, the changes you make to the new array will affect
the parent array.
For example:
>>> a2 = x.ravel()
>>> a2[0] = 98
[[98 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[98 2 3 4 5 6 7 8 9 10 11 12]
When it comes to the data science ecosystem, Python and NumPy are built with the
user in mind. One
of the best examples of this is the built-in access to
documentation. Every object contains the
reference to a string, which is known
as the docstring. In most cases, this docstring contains a quick
and concise
summary of the object and how to use it. Python has a built-in help()
function that can
help you access this information. This means that nearly any
time you need more information, you can
use help() to quickly find the
information that you need.
For example:
>>> help(max)
max(...)
For example:
In [0]: max?
Type: builtin_function_or_method
You can even use this notation for object methods and objects themselves.
Then you can obtain a lot of useful information (first details about a itself,
followed by the docstring of
ndarray of which a is an instance):
In [1]: a?
Type: ndarray
String form: [1 2 3 4 5 6]
Length: 6
File: ~/anaconda3/lib/python3.9/site-packages/numpy/__init__.py
Class docstring:
strides=None, order=None)
format of each element in the array (its byte-order, how many bytes it
to the See Also section below). The parameters given here refer to
For more information, refer to the `numpy` module and examine the
Parameters
----------
...
This also works for functions and other objects that you create. Just
remember to include a docstring
with your function using a string literal
(""" """ or ''' ''' around your documentation).
... return a * 2
In [2]: double?
Signature: double(a)
Docstring: Return a * 2
File: ~/Desktop/<ipython-input-23-b5adf20be596>
Type: function
You can reach another level of information by reading the source code of the
object you’re interested
in. Using a double question mark (??) allows you to
access the source code.
For example:
In [3]: double??
Signature: double(a)
Source:
def double(a):
'''Return a * 2'''
return a * 2
File: ~/Desktop/<ipython-input-23-b5adf20be596>
Type: function
In [4]: len?
Signature: len(obj, /)
Type: builtin_function_or_method
and :
In [5]: len??
Signature: len(obj, /)
Type: builtin_function_or_method
have the same output because they were compiled in a programming language other
than Python.
For example, this is the mean square error formula (a central formula used in
supervised machine
learning models that deal with regression):
What makes this work so well is that predictions and labels can contain
one or a thousand values.
They only need to be the same size.
In this example, both the predictions and labels vectors contain three values,
meaning n has a value of
three. After we carry out subtractions the values
in the vector are squared. Then NumPy sums the
values, and your result is the
error value for that prediction and a score for the quality of the model.
How to save and load NumPy objects
This section covers np.save, np.savez, np.savetxt,
np.load, np.loadtxt
You will, at some point, want to save your arrays to disk and load them back
without having to re-run
the code. Fortunately, there are several ways to save
and load objects with NumPy. The ndarray
objects can be saved to and loaded from
the disk files with loadtxt and savetxt functions that handle
normal
text files, load and save functions that handle NumPy binary files with
a .npy file extension,
and a savez function that handles NumPy files
with a .npz file extension.
The .npy and .npz files store data, shape, dtype, and other information
required to reconstruct the
ndarray in a way that allows the array to be
correctly retrieved, even when the file is on another
machine with different
architecture.
If you want to store a single ndarray object, store it as a .npy file using
np.save. If you want to store
more than one ndarray object in a single file,
save it as a .npz file using np.savez. You can also save
several arrays
into a single file in compressed npz format with savez_compressed.
It’s easy to save and load and array with np.save(). Just make sure to
specify the array you want to
save and a file name. For example, if you create
this array:
>>> np.save('filename', a)
>>> b = np.load('filename.npy')
>>> print(b)
[1 2 3 4 5 6]
You can save a NumPy array as a plain text file like a .csv or .txt file
with np.savetxt.
You can easily save it as a .csv file with the name “new_file.csv” like this:
You can quickly and easily load your saved text file using loadtxt():
>>> np.loadtxt('new_file.csv')
With savetxt, you can specify headers, footers, comments, and more.
>>> print(x)
>>> # You can also simply select the columns you need:
>>> print(x)
['SIA' 74000000]]
It’s simple to use Pandas in order to export your array as well. If you are new
to NumPy, you may want
to create a Pandas dataframe from the values in your
array and then write the data frame to a CSV file
with Pandas.
>>> print(df)
0 1 2 3
>>> df.to_csv('pd.csv')
You can also save your array with the NumPy savetxt method.
If you’re using the command line, you can read your saved CSV any time with a
command such as:
$ cat np.csv
# 1, 2, 3, 4
-2.58,0.43,-1.24,1.60
0.99,1.17,0.94,-0.15
0.77,0.81,-0.95,0.12
0.20,0.35,1.97,0.52
Or you can open the file any time with a text editor!
# If you're using Jupyter Notebook, you may also want to run the following
%matplotlib inline
# If you are running from a command line, you may need to do this:
# >>> plt.show()
>>> ax = fig.add_subplot(projection='3d')
>>> X, Y = np.meshgrid(X, Y)
>>> Z = np.sin(R)
To read more about Matplotlib and what it can do, take a look at
the official documentation.
For
directions regarding installing Matplotlib, see the official
installation section.
Previous Next
NumPy quickstart NumPy fundamentals