numpy.array#
An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. If object is a scalar, a 0-dimensional array containing object is returned.
dtype data-type, optional
The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence.
copy bool, optional
If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements ( dtype , order, etc.).
order <‘K’, ‘A’, ‘C’, ‘F’>, optional
Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless ‘F’ is specified, in which case it will be in Fortran order (column major). If object is an array the following holds.
F & C order preserved, otherwise most similar order
F order if input is F and not C, otherwise C order
When copy=False and a copy is made for other reasons, the result is the same as if copy=True , with some exceptions for ‘A’, see the Notes section. The default order is ‘K’.
subok bool, optional
If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).
ndmin int, optional
Specifies the minimum number of dimensions that the resulting array should have. Ones will be prepended to the shape as needed to meet this requirement.
like array_like, optional
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
An array object satisfying the specified requirements.
Return an empty array with shape and type of input.
Return an array of ones with shape and type of input.
Return an array of zeros with shape and type of input.
Return a new array with shape of input filled with value.
Return a new uninitialized array.
Return a new array setting values to one.
Return a new array setting values to zero.
Return a new array of given shape filled with value.
When order is ‘A’ and object is an array in neither ‘C’ nor ‘F’ order, and a copy is forced by a change in dtype, then the order of the result is not necessarily ‘C’ as expected. This is likely a bug.
NumPy quickstart#
You’ll need to know a bit of Python. For a refresher, see the Python tutorial.
To work the examples, you’ll need matplotlib installed in addition to NumPy.
Learner profile
This is a quick overview of arrays in NumPy. It demonstrates how n-dimensional ( \(n>=2\) ) arrays are represented and can be manipulated. In particular, if you don’t know how to apply common functions to n-dimensional arrays (without using for-loops), or if you want to understand axis and shape properties for n-dimensional arrays, this article might be of help.
Learning Objectives
After reading, you should be able to:
Understand the difference between one-, two- and n-dimensional arrays in NumPy;
Understand how to apply some linear algebra operations to n-dimensional arrays without using for-loops;
Understand axis and shape properties for n-dimensional arrays.
The Basics#
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes.
For example, the array for the coordinates of a point in 3D space, [1, 2, 1] , has one axis. That axis has 3 elements in it, so we say it has a length of 3. In the example pictured below, the array has 2 axes. The first axis has a length of 2, the second axis has a length of 3.
NumPy’s array class is called ndarray . It is also known by the alias array . Note that numpy.array is not the same as the Standard Python Library class array.array , which only handles one-dimensional arrays and offers less functionality. The more important attributes of an ndarray object are:
the number of axes (dimensions) of the array.
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m) . The length of the shape tuple is therefore the number of axes, ndim .
the total number of elements of the array. This is equal to the product of the elements of shape .
an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.
the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize .
the buffer containing the actual elements of the array. Normally, we won’t need to use this attribute because we will access the elements in an array using indexing facilities.
An example#
Array Creation#
There are several ways to create arrays.
For example, you can create an array from a regular Python list or tuple using the array function. The type of the resulting array is deduced from the type of the elements in the sequences.
A frequent error consists in calling array with multiple arguments, rather than providing a single sequence as an argument.
array transforms sequences of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on.
The type of the array can also be explicitly specified at creation time:
Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation.
The function zeros creates an array full of zeros, the function ones creates an array full of ones, and the function empty creates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is float64 , but it can be specified via the key word argument dtype .
To create sequences of numbers, NumPy provides the arange function which is analogous to the Python built-in range , but returns an array.
When arange is used with floating point arguments, it is generally not possible to predict the number of elements obtained, due to the finite floating point precision. For this reason, it is usually better to use the function linspace that receives as an argument the number of elements that we want, instead of the step:
Printing Arrays#
When you print an array, NumPy displays it in a similar way to nested lists, but with the following layout:
the last axis is printed from left to right,
the second-to-last is printed from top to bottom,
the rest are also printed from top to bottom, with each slice separated from the next by an empty line.
One-dimensional arrays are then printed as rows, bidimensionals as matrices and tridimensionals as lists of matrices.
See below to get more details on reshape .
If an array is too large to be printed, NumPy automatically skips the central part of the array and only prints the corners:
To disable this behaviour and force NumPy to print the entire array, you can change the printing options using set_printoptions .
Basic Operations#
Arithmetic operators on arrays apply elementwise. A new array is created and filled with the result.
Unlike in many matrix languages, the product operator * operates elementwise in NumPy arrays. The matrix product can be performed using the @ operator (in python >=3.5) or the dot function or method:
Some operations, such as += and *= , act in place to modify an existing array rather than create a new one.
When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as upcasting).
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class.
By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:
Universal Functions#
NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called “universal functions” ( ufunc ). Within NumPy, these functions operate elementwise on an array, producing an array as output.
Indexing, Slicing and Iterating#
One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences.
Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas:
When fewer indices are provided than the number of axes, the missing indices are considered complete slices :
The expression within brackets in b[i] is treated as an i followed by as many instances of : as needed to represent the remaining axes. NumPy also allows you to write this using dots as b[i, . ] .
The dots ( . ) represent as many colons as needed to produce a complete indexing tuple. For example, if x is an array with 5 axes, then
x[1, 2, . ] is equivalent to x[1, 2, :, :, :] ,
x[. 3] to x[:, :, :, :, 3] and
x[4, . 5, :] to x[4, :, :, 5, :] .
Iterating over multidimensional arrays is done with respect to the first axis:
However, if one wants to perform an operation on each element in the array, one can use the flat attribute which is an iterator over all the elements of the array:
Shape Manipulation#
Changing the shape of an array#
An array has a shape given by the number of elements along each axis:
The shape of an array can be changed with various commands. Note that the following three commands all return a modified array, but do not change the original array:
The order of the elements in the array resulting from ravel is normally “C-style”, that is, the rightmost index “changes the fastest”, so the element after a[0, 0] is a[0, 1] . If the array is reshaped to some other shape, again the array is treated as “C-style”. NumPy normally creates arrays stored in this order, so ravel will usually not need to copy its argument, but if the array was made by taking slices of another array or created with unusual options, it may need to be copied. The functions ravel and reshape can also be instructed, using an optional argument, to use FORTRAN-style arrays, in which the leftmost index changes the fastest.
The reshape function returns its argument with a modified shape, whereas the ndarray.resize method modifies the array itself:
If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated:
Learn Python NumPy With Examples
Everything you need to know to get started with NumPy
![]()
![]()
If you want to be a data scientist, you are gonna need to know numpy (numerical python). It is one of the most useful library of python especially, if you are crunching numbers. As majority of Data Science and Machine Learning revolves around Statistics, numpy becomes much more important to have hands-on.
Unlike other NumPy tutorials, this is a concise NumPy programming tutorial for people who think that reading is boring. I try to show everything with simple code examples; there are no long and complicated explanations with fancy words.
This section will get you started with using NumPy and you’ll be able to learn more about whatever you want after studying it.
The current post focuses on the following topics:
Installation
Arrays
Array Creation
Modifying Array
Deleting in Array
Reshaping Array
Array Sorting
Array Indexing / Slicing
Array Stacking
Array Splitting
Array Operations
Array Broadcasting
Iterating Over Arrays
Searching Arrays
Generating random numbers
Note: For this post we will be using Windows as our Operating System along with PyCharm as IDE.
Installation
To start with, we will be using PyCharm i.e Python IDE (Integrated Development Environment).
PyCharm is an IDE for professional developers. It is created by JetBrains, a company known for creating great software development tools.
There are two versions of PyCharm:
- Community — free open-source version, lightweight, good for Python and scientific development
- Professional — paid version, full-featured IDE with support for Web development as well
PyCharm provides all major features that a good IDE should provide: code completion, code inspections, error-highlighting and fixes, debugging, version control system and code refactoring. All these features come out of the box.
Personally speaking, PyCharm is my favorite IDE for Python development. The only major complaint I have heard about PyCharm is that it’s resource-intensive. If you have a computer with a small amount of RAM (usually less than 4 GB), your computer may lag.
You can download the PyCharm community version which is FREE and can be downloaded from their official website and follow the steps as shown over the video:
Once you have setup Python and PyCharm. Let’s install NumPy.
To install NumPy on PyCharm, click on File and go to the Settings. Under Settings, choose your Python project and select Python Interpreter.
You will see the + button. Click on it and search for the NumPy in the search field. You will see the NumPy package as the left side and its description, version on the right side.
Selecting numpy click on the Install Package on the left bottom. It will install the packages.
How to test if numpy is installed or not?
After the installation of the numpy on the system you can easily check whether numpy is installed or not. To do so, just use the following command to check. Inside the Pycharm write the following code and run the program for getting the output.
You will see the following output
So we are all set to start learning NumPy.
Before we move on to coding, lets just set go through some basic stuff 🙂
Arrays
In general, an array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. They are commonly used in programs to organize data so that a related set of values can be easily sorted or searched.
When it comes to NumPy, an array is a central data structure of the library. It’s 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 (data type).
An array can be indexed by a tuple of non-negative integers, by booleans, by another array, or by integers. The rank of the array is the number of dimensions. The shape of the array is a tuple of integers giving the size of the array along each dimension.
One way we can initialize NumPy arrays is from nested Python lists.
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”.
Output:
Some more information about arrays
You might occasionally hear an array referred to as a “ndarray,” which is shorthand for “N-dimensional array.” An N-dimensional array is simply an array with any number of dimensions. You might also hear 1-D, or one-dimensional array, 2-D, or two-dimensional array, and so on. The NumPy ndarray class is used to represent both matrices and vectors. A vector is an array with a single column, while a matrix refers to an array with multiple columns.
What are the attributes of an array?
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. Different arrays can share the same data, so changes made on one array might be visible in another.
Array attributes reflect information intrinsic to the array itself. If you need to get, or even set, properties of an array without creating a new array, you can often access an array through its attributes.