Last Updated:

Python numpy module

In python, all objects store a specific type of data. One of the most popular methods of structuring this data are arrays and matrices. You can work with them directly, or you can simplify your task using the numpy module.

About the module

Numpy was developed in 1955. It is based on languages such as C and Fortran. Both languages are capable of performing complex mathematical operations in the shortest possible time. Consequently, numpy has a special performance when working with arrays. The combination of Pandas, mathlib, and numpy is the main ingredient of any specialist in big data processing.

Get started with numpy

The module does not belong to the standard python library, and therefore requires additional installation through the pip-installer. To install numpy, open a command prompt and type the following command:

pipinstallnumpy

 

The following error may occur during installation:

 

Python numpy module

This means that the installer must be updated. The problem is solved easily. Enter "python -m pipinstall –upgradepip", and then re-enter the previous command. Ready! This library is now installed on your computer and can be imported into your project. To do this, add the following line to the beginning of the code:

1. importnumpy

Examples of using numpy

Most often, the module is used in Datascience for big data analysis. We'll get by with a simpler example:

importmatplotlib.pyplot as plt
importnumpy as np
x = np.linspace(-5, 5, 100)
def sigmoid(alpha):
return1 / ( 1 + np.exp(- alpha * x) )
dpi = 80
fig = plt.figure(dpi = dpi, figsize = (512 / dpi, 384 / dpi) )
plt.plot(x, sigmoid(0.5), ‘ro-‘)
plt.plot(x, sigmoid(1.0), ‘go-‘)
plt.plot(x, sigmoid(2.0), ‘bo-‘)
plt.legend([‘A = 0.5’, ‘A = 1.0’, ‘A = 2.0’], loc = ‘upper left’)
fig.savefig(‘sigmoid.png’)

Thanks to the module, I did not have to manually prescribe cycles for placing dots on the chart, everything was calculated automatically. Convenient and fast.

  • In general, numpy is the right solution if you need to:
  • Perform operations on arrays and matrices
  • Perform complex arithmetic problems with big data
  • Build statistics based on data

Math in numpy

With python lists, it is unbearably difficult to carry out mathematical operations. The fact is that when using the signs +, *, - in relation to the list, the process of concatenation, and not calculation, occurs.

Example:

list1 = [7, 8, 9]
number = 3
print(list1 * number) # [7, 8, 9, 7, 8, 9, 7, 8, 9]
print(list1 + number) #Typeerror - unable to join list and number

But if we initially turn list1 into an array, the situation will change dramatically:

list1 = [7, 8, 9]
number = 3
array1 = numpy.array(list1)
print(array1 * number) # [21 24 27]
print( array1 + number) # [10 11 12]
print(array1 - number) # [4 5 6]

As you can see, when working with arrays, all mathematical operations work as intended.
The following is a list of some of the mathematical functions that are available in the numpy module:

  1. numpy.log(n) – Search for the natural logarithm of array elements;
  2. np.sin(n) – Sine of each element of the array;
  3. np.arange(n) – create a sequence from 0 to n;
  4. np.cos(n) – cosine of each element of the array;
  5. np.hypot(a, b) – вычисление гипотенузы по двум катетам. c2 = a2 + b2;
  6. np.rint(n) – round up to the nearest number.

The module also supports array comparison. Example:

array1 = numpy.array([1, 2, 4, 5, 6])
array2 = numpy.array([1, 2, 3, 5, 7])
print(array1 == array2) # [ True True False True False]

Working with the matrix

Contrary to the legendary film, matrices are just a sequence of data that are arranged horizontally, vertically, and in depth. Any two-dimensional array is already a matrix.

As we remember from the school course Algebra: Matrices can be added, multiplied, transposed. If we considered the first two options above, then we will consider transposition now:

importnumpy as np
a = np.array([[0, 1, 2], [4, 5, 6]])
a = a.transpose()
print(a) # [[0 4]
[1 5]
[2 6]]

Recall that transposition is the exchange of places of rows and columns, that is:

0 1 2
4 5 6

After transposition, it becomes:

0 4
1 5
2 6

Arrays in numpy

Above, we've seen a few examples of creating arrays. Basically, all the examples were reduced to mathematical operations, but the potential of the module is much higher. You can display individual rows, columns, or items. This is done through square brackets. Example:

a = np.array([[1, 3, 4], [5, 6, 7]])
print(a[0]) # print the first line
print(a[0][0]) # print the first element of the first line

List of some of the functions of the module for working with arrays

  • !=, <, <=, >, >= are logical operations. Return True or False for each element in the array.
  • Numpy.sum(n) – sum of all elements of the array
  • n.min(), n.max() – find a larger and smaller number in an array
  • np.zeros(n) – Returns a zero-filled array up to n element
  • np.ones(n) – Returns the unit-filled array from the nelement

Indexing arrays

If you still don't understand how two-dimensional arrays are indexed, then that's okay. Let's look at it now. Imagine a two-dimensional array. It looks like this:

1 2 3
4 5 6
7 8 9

  • 1 2 3 is the first line
  • 1 4 7 is the first column
  • 4 is the first element of the second line.

Now let's look from the point of view of python. In the program code, it looks like this:

Array = numpy.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

1 2 3 are the three elements of the first nested array. They can be invoked using the Array[0] command. To output 4 elements of row 2, use the following Array[2][4] command. It will be more difficult to display the column:

i = 1
print(Array[:, i:i+1])

Matrix depth

Matrices have rows, columns, and a third vector that leads deep into the array. An example of such a three-dimensional matrix:

Array = numpy.array([
[[1,2,3],[4,5,6], [7,8,9]],
[[10,11,12], [13,14,15], [16,17,18]],
[[19,20,21], [22,23,24],[25,26,27]]

])

Complex design? Yes, but, fortunately, three-dimensional arrays are rarely used, and in those cases they are clogged by the user. But still, let's break down this design. How to refer to the 3rd elements of the depth of the 3rd element of the first line. To do this, we just need to specify array_name[line_number][element_number][element_number_deep].

Example:

Array[1][2][2] # 3

Working with sound

In conclusion, we will demonstrate the use of the numpy library to work with sound. The following code element:

importnumpy as np
fromscipy.io.wavfile import write

data = np.random.uniform(-1,1,44100) # 44100 random samples between -1 and 1
scaled = np.int16(data/np.max(np.abs(data)) * 32767)
write(‘test.wav’, 44100, scaled)

Through the array sequence, we encoded the sound file. When you start the program, white noise appears. You can play with a value of 44100. By changing it, you will also change the sound of the final audio file.

Conclusion

Numpy has a rich functionality and wide application in the world of programming. If you are learning pythonrady of neural networks, big data analysis, solving mathematical problems of similar activity, then numpy this must have for you.