Welcome to the absolute beginner’s guide to NumPy!
NumPy (Numerical Python) is an open source Python library that’s
widely used in science and engineering. The NumPy library contains
multidimensional array data structures, such as the homogeneous, N-dimensional
ndarray, and a large library of functions that operate efficiently on these
data structures. Learn more about NumPy at What is NumPy,
and if you have comments or suggestions, please
reach out!
How to import NumPy
After installing NumPy, it may be imported
into Python code like:
importnumpyas
np
This widespread convention allows access to NumPy features with a short,
recognizable prefix (np.) while distinguishing NumPy features from others
that have the same name.
Reading the example code
Throughout the NumPy documentation, you will find blocks that look like:
Text preceded by >>> or ... is input, the code that you would
enter in a script or at a Python prompt. Everything else is output, the
results of running your code. Note that >>> and ... are not part of the
code and may cause an error if entered at a Python prompt.
To run the code in the examples, you can copy and paste it into a Python script or
REPL, or use the experimental interactive examples in the browser provided in various
locations in the documentation.
Why use NumPy?
Python lists are excellent, general-purpose containers. They can be
“heterogeneous”, meaning that they can contain elements of a variety of types,
and they are quite fast when used to perform individual operations on a handful
of elements.
Depending on the characteristics of the data and the types of operations that
need to be performed, other containers may be more appropriate; by exploiting
these characteristics, we can improve speed, reduce memory consumption, and
offer a high-level syntax for performing a variety of common processing tasks.
NumPy shines when there are large quantities of “homogeneous” (same-type) data
to be processed on the CPU.
What is an “array”?
In computer programming, an array is a structure for storing and retrieving
data. We often talk about an array as if it were a grid in space, with each
cell storing one element of the data. For instance, if each element of the
data were a number, we might visualize a “one-dimensional” array like a
list:
1520
A two-dimensional array would be like a table:
181537262019
A three-dimensional array would be like a set of tables, perhaps stacked
as though they were printed on separate pages. In NumPy, this idea is
generalized to an arbitrary number of dimensions, and so the fundamental
array class is called ndarray: it represents an “N-dimensional
array”.
Most NumPy arrays have some restrictions. For instance:
All elements of the array must be of the same type of data.
Once created, the total size of the array can’t change.
The shape must be “rectangular”, not “jagged”; e.g., each row of
a two-dimensional array must have the same number of columns.
When these conditions are met, NumPy exploits these characteristics to
make the array faster, more memory efficient, and more convenient to use than
less restrictive data structures.
For the remainder of this document, we will use the word “array” to refer to
an instance of ndarray.
Array fundamentals
One way to initialize an array is using a Python sequence, such as a list.
For example:
Elements of an array can be accessed in various ways. For instance, we can access an
individual element of this array as we would access an element in the original
list: using the integer index of the element within square brackets.
>>> a[0]1
Like the original list, the array is mutable.
>>> a[0]=10>>> aarray([10, 2, 3, 4, 5, 6])
Also like the original list, Python slice notation can be used for indexing.
>>> a[:3]array([10, 2, 3])
One major difference is that slice indexing of a list copies the elements into
a new list, but slicing an array returns a view: an object that refers to the
data in the original array. The original array can be mutated using the view.
In NumPy, a dimension of an array is sometimes referred to as an “axis”. This
terminology may be useful to disambiguate between the dimensionality of an
array and the dimensionality of the data represented by the array. For
instance, the array a could represent three points, each lying within a
four-dimensional space, but a has only two “axes”.
Another difference between an array and a list of lists is that an
element of the array can be accessed by specifying the index along each
axis within a single set of square brackets, separated by commas.
For instance, the element 8 is in row 1 and column 3:
>>> a[1,3]8
Array attributes
This section covers thendim, shape, size, anddtypeattributes of an array.
The number of dimensions of an array is contained in the ndim attribute.
>>> a.ndim2
The shape of an array is a tuple of non-negative integers that specify the
number of elements along each dimension.
>>> a.shape(3, 4)>>> len(a.shape)==a.ndimTrue
The fixed, total number of elements in array is contained in the size
attribute.
This section coversnp.zeros(), np.ones(),
np.empty(), np.arange(), np.linspace()
Besides creating an array from a sequence of elements, you can easily create an
array filled with 0’s:
>>> np.zeros(2)array([0., 0.])
Or an array filled with 1’s:
>>> np.ones(2)array([1., 1.])
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!
>>> # Create an empty array with 2 elements>>> np.empty(2)array([3.14, 42. ]) # may vary
You can create an array with a range of elements:
>>> 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:
This section coversndarray.ndim, ndarray.size, ndarray.shape
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.
ndarray.shape will display a tuple of integers that indicate the number of
elements stored along each dimension of the array. If, for example, you have a
2-D array with 2 rows and 3 columns, the shape of your array is (2,3).
To find the number of dimensions of the array, run:
>>> array_example.ndim3
To find the total number of elements in the array, run:
>>> array_example.size24
And to find the shape of your array, run:
>>> array_example.shape(3, 2, 4)
Can you reshape an array?
This section coversarr.reshape()
Yes!
Using arr.reshape() will return a reshaped 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.
If you start with this array:
>>> 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:
shape 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.
order:C means to read/write the elements using C-like index order,
F means to read/write the elements using Fortran-like index order, A
means to read/write the elements in Fortran-like index order if a is Fortran
contiguous in memory, C-like order otherwise. (This is an optional parameter and
doesn’t need to be specified.)
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.
How to convert a 1D array into a 2D array (how to add a new axis to an array)
This section coversnp.newaxis, np.expand_dims
You can use np.newaxis and np.expand_dims to increase the dimensions of
your existing array.
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.
For example, if you start with this array:
>>> a=np.array([1,2,3,4,5,6])>>> a.shape(6,)
You can use np.newaxis to add a new axis:
>>> a2=a[np.newaxis,:]>>> a2.shape(1, 6)
You can explicitly convert a 1D array to 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:
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 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.
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:
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.
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).
Views are an important NumPy concept! NumPy functions, as well as operations
like indexing and slicing, will return views whenever possible. This saves
memory and is faster (no copy of the data has to be made). However it’s
important to be aware of this - modifying data in a view also modifies the
original array!
This section covers addition, subtraction, multiplication, division, and more
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.
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=np.array([1,2,3,4])>>> a.sum()10
To add the rows or the columns in a 2D array, you would specify the axis.
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:
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.
This section covers maximum, minimum, sum, mean, product, standard deviation, and more
NumPy also performs aggregation functions. In addition to min, max, and
sum, you can easily run mean to get the average, prod to get the
result of multiplying the elements together, std to get the standard
deviation, and more.
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.
You can aggregate matrices the same way you aggregated vectors:
>>> data.max()6>>> data.min()1>>> 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:
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.
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)array([1., 1., 1.])>>> np.zeros(3)array([0., 0., 0.])>>> rng=np.random.default_rng()# the simplest way to generate random numbers>>> rng.random(3)array([0.63696169, 0.26978671, 0.04097352])
You can also use ones(), zeros(), and random() to create
a 2D array if you give them a tuple describing the dimensions of the matrix:
Read more about creating arrays, filled with 0’s, 1’s, other values or
uninitialized, at array creation routines.
Generating random numbers
The use of random number generation is an important part of the configuration
and evaluation of many numerical and machine learning algorithms. Whether you
need to randomly initialize weights in an artificial neural network, split data
into random sets, or randomly shuffle your dataset, being able to generate
random numbers (actually, repeatable pseudo-random numbers) is essential.
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.
You can generate a 2 x 4 array of random integers between 0 and 4 with:
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.
If the axis argument isn’t passed, your 2D array will be flattened.
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.
To learn more about finding the unique elements in an array, see unique.
Transposing and reshaping a matrix
This section coversarr.reshape(), arr.transpose(), arr.T
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.
To learn more about transposing and reshaping arrays, see transpose and
reshape.
How to reverse an array
This section coversnp.flip()
NumPy’s np.flip() function allows you to flip, or reverse, the contents of
an array along an axis. When using np.flip(), specify the array you would like
to reverse and the axis. If you don’t specify the axis, NumPy will reverse the
contents along all of the axes of your input array.
Reversing a 1D array
If you begin with a 1D array like this one:
>>> arr=np.array([1,2,3,4,5,6,7,8])
You can reverse it with:
>>> reversed_arr=np.flip(arr)
If you want to print your reversed array, you can run:
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):
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.
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)Help on built-in function max in module builtins:max(...) max(iterable, *[, default=obj, key=func]) -> value max(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more ...arguments, return the largest argument.
Because access to additional information is so useful, IPython uses the ?
character as a shorthand for accessing this documentation along with other
relevant information. IPython is a command shell for interactive computing in
multiple languages.
You can find more information about IPython here.
For example:
In [0]: max?max(iterable, *[, default=obj, key=func]) -> valuemax(arg1, arg2, *args, *[, key=func]) -> valueWith a single iterable argument, return its biggest item. Thedefault keyword-only argument specifies an object to return ifthe provided iterable is empty.With two or more arguments, return the largest argument.Type: builtin_function_or_method
You can even use this notation for object methods and objects themselves.
Let’s say you create this array:
>>> a=np.array([1,2,3,4,5,6])
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: ndarrayString form: [1 2 3 4 5 6]Length: 6File: ~/anaconda3/lib/python3.9/site-packages/numpy/__init__.pyDocstring: <no docstring>Class docstring:ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)An array object represents a multidimensional, homogeneous arrayof fixed-size items. An associated data-type object describes theformat of each element in the array (its byte-order, how many bytes itoccupies in memory, whether it is an integer, a floating point number,or something else, etc.)Arrays should be constructed using `array`, `zeros` or `empty` (referto the See Also section below). The parameters given here refer toa low-level method (`ndarray(...)`) for instantiating an array.For more information, refer to the `numpy` module and examine themethods and attributes of an array.Parameters----------(forthe__new__
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).
For example, if you create this function:
>>> defdouble(a):... '''Return a * 2'''... returna*2
You can obtain information about the function:
In [2]: double?Signature: double(a)Docstring: Return a * 2File: ~/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 * 2File: ~/Desktop/<ipython-input-23-b5adf20be596>Type: function
If the object in question is compiled in a language other than Python, using
?? will return the same information as ?. You’ll find this with a lot of
built-in objects and types, for example:
In [4]: len?Signature: len(obj, /)Docstring: Return the number of items in a container.Type: builtin_function_or_method
and :
In [5]: len??Signature: len(obj, /)Docstring: Return the number of items in a container.Type: builtin_function_or_method
have the same output because they were compiled in a programming language other
than Python.
Working with mathematical formulas
The ease of implementing mathematical formulas that work on arrays is one of
the things that make NumPy so widely used in the scientific Python community.
For example, this is the mean square error formula (a central formula used in
supervised machine learning models that deal with regression):
Implementing this formula is simple and straightforward in NumPy:
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.
You can visualize it this way:
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 coversnp.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 an 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:
>>> a=np.array([1,2,3,4,5,6])
You can save it as “filename.npy” with:
>>> np.save('filename',a)
You can use np.load() to reconstruct your array.
>>> b=np.load('filename.npy')
If you want to check your array, you can run:
>>> 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.
For example, if you create this array:
>>> csv_arr=np.array([1,2,3,4,5,6,7,8])
You can easily save it as a .csv file with the name “new_file.csv” like this:
>>> np.savetxt('new_file.csv',csv_arr)
You can quickly and easily load your saved text file using loadtxt():
The savetxt() and loadtxt() functions accept additional optional
parameters such as header, footer, and delimiter. While text files can be easier
for sharing, .npy and .npz files are smaller and faster to read. If you need more
sophisticated handling of your text file (for example, if you need to work with
lines that contain missing values), you will want to use the genfromtxt
function.
With savetxt, you can specify headers, footers, comments, and more.
It’s simple to read in a CSV that contains existing information. The best and
easiest way to do this is to use
Pandas.
>>> importpandasaspd>>> # If all of your columns are the same type:>>> x=pd.read_csv('music.csv',header=0).values>>> print(x)[['Billie Holiday' 'Jazz' 1300000 27000000] ['Jimmie Hendrix' 'Rock' 2700000 70000000] ['Miles Davis' 'Jazz' 1500000 48000000] ['SIA' 'Pop' 2000000 74000000]]>>> # You can also simply select the columns you need:>>> x=pd.read_csv('music.csv',usecols=['Artist','Plays']).values>>> print(x)[['Billie Holiday' 27000000] ['Jimmie Hendrix' 70000000] ['Miles Davis' 48000000] ['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.
If you need to generate a plot for your values, it’s very simple with
Matplotlib.
For example, you may have an array like this one:
>>> a=np.array([2,1,5,7,4,6,8,14,10,9,18,20,22])
If you already have Matplotlib installed, you can import it with:
>>> importmatplotlib.pyplotasplt# If you're using Jupyter Notebook, you may also want to run the following# line of code to display your code in the notebook:%matplotlib inline
All you need to do to plot your values is run:
>>> plt.plot(a)# If you are running from a command line, you may need to do this:# >>> plt.show()
For example, you can plot a 1D array like this:
>>> x=np.linspace(0,5,20)>>> y=np.linspace(0,10,20)>>> plt.plot(x,y,'purple')# line
With Matplotlib, you have access to an enormous number of visualization options.