Array in Python (Python)

Python is a high-level general-purpose programming language. It supports not only OOP, but also structural, functional, imperative, aspect-oriented programming. The standard library contains many tools for working with network protocols, text encodings, multimedia formats, and for developing cross-platform applications.

Array in Python

A one-dimensional array is a list of elements.

Arrays in Python

The list values ​​are indicated between the square brackets [], separated by commas. Any item is called by index. Elements can be assigned new values.

This is what an empty list looks like:

  • a = []

The array of strings in Python looks like this:

  • Prime = ['string1', 'string2', 'string3']
  • Prime [1] = 'string2'; // true

The len () function returns the number of elements within a list.

  • len (Prime) == 4; // true

To list the elements of an array, use the for loop. Its difference from Pascal is that iterates over the elements, not their indices.

  • for elem in [1, 4, 67]

To create a loop, a list popup generator is used. It is written in the form [array value for variable name in number of elements];

A two-dimensional array in Python is created using nested generators. It should look something like this:

  • [[0 for j in range (m)] for i in range (n)]

Creating an array in NumPy

To create and modify arrays in Python, the NumPy library is used.

YP Python

It supports a multidimensional array and matrices, has a large set of packages for solving mathematical problems. And also provides work with homogeneous multidimensional arrays and matrices. To be able to use the functions of this package, you must import it.

  • import numpy as np

One of the easiest ways to set an array in Python is to use the array () function. It creates an object of type ndarray.

  • array = np.array (/ * many elements * /)

Array is now of type ndarray. This can be verified by the array.type () function. She took as an argument the name of the created array. The answer will return - <class 'numpy.ndarray'>.

To override a type, you need to use dtype = np.complex at the creation stage.

  • array2 = np.array ([/ * elements * /, dtype = np.complex)

If you need to specify an array, but its elements are unknown at this stage, it is filled with zeros by the zeros () function. You can create an array of units with the ones () function. The arguments are the number of nested arrays and the number of elements inside.

  • np.zeros (2, 2, 2)

It will create two arrays inside that contain 2 elements each.

  • array ([
  • [[0, 0]]
  • [[0, 0]]]
  • )

To print an array to the screen, use the print () function. If the array is too large to print, NumPy hides the center portion and displays only the extreme values.

To see the entire array, the set_printoptions () function is used. By default, only the first 1000 items are displayed. This value is specified as an argument with the threshold keyword.

Basic NumPy Operations

Any actions on the elements of the array in Python require the creation of a new array.

Numpy library

The created array contains elements obtained as a result of performing some actions on them. Arrays can only interact if they are the same size. For instance:

  • array1 = np.array ([[[1, 2, 3], [1, 2, 3]])
  • array2 = np.array ([[[1, 2, 3], [1, 2, 3], [1, 2, 3]])

When array1 + array2 is executed, the compiler will throw an error, because the size of the first array is 2, and the size of the second is 3.

  • array1 = np.array ([1, 2, 5, 7])
  • array2 = arange ([1, 5, 1])

Array1 + array2 will return an array with elements 2, 4, 8, 11. An error will not occur, because the size of both is the same.

Instead of manual addition, you can use a function that is part of the ndarray sum () class.

  • np.array (array1 + array1) == array1 + array2

The ndarray class provides a large library of methods for mathematical operations. They are specified as np. Method name (variable name).

The form

The size of the array in Python determines the shape. To check the current shape, use the shape () method.

One-dimensional, two-dimensional and three-dimensional array

An array with two and three elements has the form (2, 2, 3). It will change if arguments are specified in shape (). The number of subarrays will be used as the first, the second - the dimension of each subarray. The reshape () function performs the same operation. Its parameters determine the number of rows and columns.

There are methods for manipulating the form. For example, ravel () from a multidimensional array does one-dimensional by arranging internal values ​​in ascending order sequentially. The transpose () function swaps the rows and columns of a multidimensional array.

Slices

Often you have to work not with the whole array, but only with some of its elements. For these purposes, in Python there is a method "Slice" (slice). It replaced the enumeration of elements with a for loop.

Slices in Python

The method opens up wide possibilities for obtaining a copy of the array in Python. All manipulations are performed in this form [start: stop: step]. Here, the start value indicates the index of the element from which the count begins, the stop value is the last element, the step size is the number of elements to skip at each iteration. By default, start is zero, that is, the count starts from the zero element of the list, stop is the index of the last element in the list, the step is one, that is, iterates through each one. If passed to the function without arguments, the list is copied completely from beginning to end.

For example, we have an array:

  • mas = [1, 2, 3, 4]

To copy it, use mas [:]. The function will return a sequence of elements [1, 2, 3, 4]. If the argument is a negative value, for example -3, the function will return elements with indices from the third to the last.

  • mas [-3]; //[4]

After the double colon, the step of the elements copied in the array is indicated. For example, mas [:: 2] will return an array [1, 3]. If a negative value is specified, for example, [:: - 2] the count will start from the end, and we will get [3, 1].

Using the slice method, you can flexibly work with nested lists. For a two-dimensional array in Python, [:, 2] means that every third element of all arrays will be returned. If you specify [: 2] - the first two will return.

Copy

A copy is obtained using the slices described above. In Python, copying through assignment does not work, because in this way not the objects themselves are transferred, but only the links. This means that creating an array with np.arange (10) values ​​and assigning array2 = array1, we get two objects with the same values ​​but different names, in this case array1 and array2. Changing the shape of one of them will affect the second. The array1.shape (3, 4) function will change the form of array2.

  • array1.shape () == (3, 4); // true
  • array2.shape () == (3, 4); // true

The view () function creates different objects with the same data. For example, we have a certain array array, to which we apply the view () function

  • array.view ()

We assign the resulting value to the second array2 and we see that these are different objects, but they have the same data. We check:

  • array2 is array1; // false

If we change the shape of one of the arrays, it does not change in the second.

  • array1.shape (2, 6)
  • array1 == array2; // true

Merge, split

Arrays can be combined among themselves. This is done along axes or rows. The hstack () function joins them row by row, and vstack () joins them row by column.

Using the column_stack () function, you can combine arrays in arguments into one one-dimensional. Similarly, column_stack () works row_stack (), but concatenates rows, not columns. To split the array horizontally, the hsplit () function is used, and vsplit () - vertically.


All Articles