📜 ⬆️ ⬇️

NumPy in Python. Part 1

Translator's Preface


Good day, Habr. I run a series of articles that are a translation of a small mana on numpy, a reference . Enjoy reading.



Introduction


NumPy is an open-source module for python that provides general mathematical and numerical operations in the form of pre-compiled, fast functions. They are combined in high-level packages. They provide functionality that can be compared with MatLab functionality. NumPy (Numeric Python) provides basic methods for manipulating large arrays and matrices. SciPy (Scientific Python) extends the numpy functionality with a huge collection of useful algorithms, such as minimization, Fourier transform, regression, and other applied mathematical techniques.

Installation


If you have Python (x, y) ( Translator's Note: Python (x, y), this is a distribution of free scientific and engineering software for numerical calculations, analysis and visualization of data based on the Python programming language and a large number of modules (libraries)) on the Windows platform, then you are ready to start. If not, then after installing python, you need to install the packages yourself, first NumPy and then SciPy. Installation is available here . Follow the installation on the page, everything is very clear.
')

Some additional information


The NumPy and SciPy community supports online tutorials, including guides and tutorials, here: docs.scipy.org/doc.

Import numpy module

There are several ways to import. The standard method is to use a simple expression:

>>> import numpy 

However, for a large number of numpy function calls, it becomes tedious to write numpy.X again and again. Instead, it is much easier to do it like this:

 >>> import numpy as np 

This expression allows us to access numpy objects using np.X instead of numpy.X. You can also import numpy directly into the used namespace, in order not to use functions through the dot at all, but to call them directly:

 >>> from numpy import * 

However, this option is not welcome in python programming, as it removes some of the useful structures that the module provides. Until the end of this tutorial, we will use the second import option (import numpy as np).

Arrays


The main feature of numpy is the array object. Arrays are similar to lists in python, except for the fact that the elements of an array must have the same data type as float and int. With arrays, you can perform numeric operations with a large amount of information many times faster and, most importantly, much more efficiently than with lists.

Creating an array from the list:

 a = np.array([1, 4, 5, 8], float) >>> a array([ 1., 4., 5., 8.]) >>> type(a) <class 'numpy.ndarray'> 

Here, the array function takes two arguments: a list for converting to an array and a type for each element. All elements can be accessed and manipulated as you would with regular lists:

 >>> a[:2] array([ 1., 4.]) >>> a[3] 8.0 >>> a[0] = 5. >>> a array([ 5., 4., 5., 8.]) 

Arrays can be multidimensional. Unlike lists, you can specify commands in brackets. Here is an example of a two-dimensional array (matrix):

 >>> a = np.array([[1, 2, 3], [4, 5, 6]], float) >>> a array([[ 1., 2., 3.], [ 4., 5., 6.]]) >>> a[0,0] 1.0 >>> a[0,1] 2.0 

Array slicing works with multidimensional arrays in the same way as with one-dimensional arrays, applying each slice as a filter for the set dimension. Use ":" in the dimension to indicate the use of all elements of this dimension:

 >>> a = np.array([[1, 2, 3], [4, 5, 6]], float) >>> a[1,:] array([ 4., 5., 6.]) >>> a[:,2] array([ 3., 6.]) >>> a[-1:, -2:] array([[ 5., 6.]]) 

The shape method returns the number of rows and columns in the matrix:

 >>> a.shape (2, 3) 

The dtype method returns the type of variables stored in the array:

 >>> a.dtype dtype('float64') 

Here, float64 is the numeric data type in numpy, which is used to store double-precision real numbers. So what about float in Python.

The len method returns the length of the first dimension (axis):

 a = np.array([[1, 2, 3], [4, 5, 6]], float) >>> len(a) 2 

The in method is used to check for the presence of an element in an array:

 >>> a = np.array([[1, 2, 3], [4, 5, 6]], float) >>> 2 in a True >>> 0 in a False 

Arrays can be reformed using the method that defines a new multidimensional array. Following the following example, we reformat a one-dimensional array of ten elements into a two-dimensional array consisting of five rows and two columns:

 >>> a = np.array(range(10), float) >>> a array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]) >>> a = a.reshape((5, 2)) >>> a array([[ 0., 1.], [ 2., 3.], [ 4., 5.], [ 6., 7.], [ 8., 9.]]) >>> a.shape (5, 2) 

Note that the reshape method creates a new array, and does not modify the original one.

Keep in mind that tying names in python also works with arrays. The copy method is used to create a copy of an existing array in memory:

 >>> a = np.array([1, 2, 3], float) >>> b = a >>> c = a.copy() >>> a[0] = 0 >>> a array([0., 2., 3.]) >>> b array([0., 2., 3.]) >>> c array([1., 2., 3.]) 

Lists can also be created from arrays:

 >>> a = np.array([1, 2, 3], float) >>> a.tolist() [1.0, 2.0, 3.0] >>> list(a) [1.0, 2.0, 3.0] 

You can also convert the array to a binary string (that is, not a human-readable form). Use the tostring method for this. The fromstring method works in reverse conversion. These operations are sometimes useful for storing large amounts of data in files that can be read in the future.

 >>> a = array([1, 2, 3], float) >>> s = a.tostring() >>> s '\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08@' >>> np.fromstring(s) array([ 1., 2., 3.]) 

Filling an array with the same value.

 >>> a = array([1, 2, 3], float) >>> a array([ 1., 2., 3.]) >>> a.fill(0) >>> a array([ 0., 0., 0.]) 

Transposing arrays is also possible, and a new array is created:

 >>> a = np.array(range(6), float).reshape((2, 3)) >>> a array([[ 0., 1., 2.], [ 3., 4., 5.]]) >>> a.transpose() array([[ 0., 3.], [ 1., 4.], [ 2., 5.]]) 

A multidimensional array can be converted to one-dimensional using the flatten method:

 >>> a = np.array([[1, 2, 3], [4, 5, 6]], float) >>> a array([[ 1., 2., 3.], [ 4., 5., 6.]]) >>> a.flatten() array([ 1., 2., 3., 4., 5., 6.]) 

Two or more arrays can be concatenated using the concatenate method:

 >>> a = np.array([1,2], float) >>> b = np.array([3,4,5,6], float) >>> c = np.array([7,8,9], float) >>> np.concatenate((a, b, c)) array([1., 2., 3., 4., 5., 6., 7., 8., 9.]) 

If the array is not one-dimensional, you can specify the axis along which the connection will occur. By default (without setting the axis values), the connection will occur in the first dimension:

 >>> a = np.array([[1, 2], [3, 4]], float) >>> b = np.array([[5, 6], [7,8]], float) >>> np.concatenate((a,b)) array([[ 1., 2.], [ 3., 4.], [ 5., 6.], [ 7., 8.]]) >>> np.concatenate((a,b), axis=0) array([[ 1., 2.], [ 3., 4.], [ 5., 6.], [ 7., 8.]]) >>> np.concatenate((a,b), axis=1) array([[ 1., 2., 5., 6.], [ 3., 4., 7., 8.]]) 

Finally, the dimension of the array can be increased by using the newaxis constant in square brackets:

 >>> a = np.array([1, 2, 3], float) >>> a array([1., 2., 3.]) >>> a[:,np.newaxis] array([[ 1.], [ 2.], [ 3.]]) >>> a[:,np.newaxis].shape (3,1) >>> b[np.newaxis,:] array([[ 1., 2., 3.]]) >>> b[np.newaxis,:].shape (1,3) 

Notice here each array is two-dimensional; created with newaxis has dimension one. The newaxis method is suitable for conveniently creating proper-dimensional arrays in vector and matrix mathematics.

This is the end of the first part of the translation. Thanks for attention.

Source: https://habr.com/ru/post/352678/


All Articles