Understanding: What is Numpy in Python?

 


What is numpy in python

Numpy is often used in Data Science and Machine Learning .

But..

Many people don't understand, what exactly is Numpy?

Why do we use Numpy?

and how do you use it?

Let's learn!

What is Numpy?

NumPy (Numerical Python) is a Python library that focuses on scientific computing . 1

Simply put:

Numpy provides ready-to-use functions to make it easier for us to carry out scientific calculations such as matrices, algebra, statistics, and so on.

Why do we need Numpy?

Doesn't Python already have lists and math modules , right? 🤔

That's right, we can use lists and math for scientific calculations. However, it is still incomplete, because we have to make some calculation operations manually.

Example:

We want to calculate the sum of each element in the list.

# kita punya list a dan b
a = [1, 2, 3]
b = [4, 5, 6]

# lalu kita jumlahkan
hasil = a + b

print(hasil) # [1, 2, 3, 4, 5, 6]

The results are not what we expected. Each element should be added up, but instead the lists are combined.

If we want to add up, then we have to create a formula or function manually like this:

def add(list_a, list_b):
  result = []
  for first, second in zip(list_a, list_b):
    result.append(first + second)
  return result

Therefore, so that you don't have to bother creating it manually from scratch... it's better to use the existing one from Numpy.

Apart from that, Numpy's performance is also faster than lists. The problem is that the Numpy library is written in C and partly Python.

OK... then how do you install and use Numpy?

Let's continue studying:

How to Install Numpy

We can install Numpy with the package manager pip.

Run the following command in Terminal or CMD to install Numpy:

pip install numpy

Just run this command once, then Numpy will be installed on your computer.

After successfully installing, next we learn:

How to Use Numpy

We have to import Numpy first so it can be used in the program.

Example:

import numpy as np

In this example, we import numpyand use alias names npso we don't type too long hehe.

After that, then we can use the functions in np(Numpy).

Example:

Creating arrays with Numpy

my_array = np.array([1, 2, 3, 4])

The variable my_arraywill be an array object ( ndarray).

Don't be confused by the terms ndarray..

..this means n dimension array .

In simple terms, it means: multi-dimensional array.

Practice: Creating an Array with Numpy

Create a new file named array_numpy.pythen fill it with the following code:

import numpy as np

# membuat array
nilai_siswa = np.array([85, 55, 40, 90])

# mengakses data pada array
print(nilai_siswa[3])

After that, try running it.

So the result is:

Example of a list with Numpy

In this exercise, we can find out...

..if you have an array in Numpy, the way to access the data is the same as a list.

Creating a Matrix with Numpy

Matrices in program code are usually created as two-dimensional arrays, this is because matrices consist of rows and columns.

Matrix Anatomy

The first dimension acts as a column and the second dimension acts as a row.

Example:

matriks = [[1,2,3],
           [4,5,6],
           [7,8,9]]

In this example we create a two-dimensional list with list.

If you want to create a matrix with Numpy, then we can use the function array()and enter a list of matrices.

Example:

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

The way to access the data is also the same as a list.

For example, if we want to get a number 5, we can access it by:

print(matrik_np[1][1])

This is because the numbers 5are in the 1st column and 1st row.

Remember, a list or array's index always starts from zero.

What if you want to take numbers 3?

Easy…

Single write like this:

print(matrik_np[0][2])

This is because the numbers 3are in the 0th column and 2nd row.

It's easy right?

I assume you already understand.

Next we will learn matrix operations with Numpy.

Matrix Operations with Numpy

If you use lists in Python for matrix operations, then you will create the operations manually by looping.

Examples like this:

# Program to add two matrices using nested loop

X = [[12,7,3],
    [4,5,6],
    [7,8,9]]

Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]

result = [[0,0,0],
         [0,0,0],
         [0,0,0]]

# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[i][j] = X[i][j] + Y[i][j]

for r in result:
   print(r)

This is certainly troublesome, because we have to make the operation ourselves.

But don't worry...

..in Numpy we can perform matrix operations easily, as easy as performing operations on numbers.

Let's try it!

Matrix addition

Create a new file with the name penjumlahan_matrik.pythen fill it with the following code:

penjumlahan_matrik.py
import numpy as np

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

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

hasil = matrik_a + matrik_b

print(hasil)

After that, try running it!

So the result is:

Matrix addition operation in python

Matrix reduction

Create a new file with the name pengurangan_matrik.pythen fill it with the following code:

pengurangan_matrik.py
import numpy as np

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

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

hasil = matrik_a - matrik_b

print(hasil)

After that, try running it!

So the result is:

Matrix subtraction operations in python

Matrix multiplication

Create a new file with the name perkalian_matrik.pythen fill it with the following code:

perkalian_matrik.py
import numpy as np

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

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

hasil = matrik_a * matrik_b

print(hasil)

After that, try running it!

So the result is:

Matrix multiplication operations in Python

Matrix division

Create a new file with the name pembagian_matrik.pythen fill it with the following code:

pembagian_matrik.py
import numpy as np

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

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

hasil = matrik_a / matrik_b

print(hasil)

After that, try running it!

So the result is:

Matrix division operations in Python

Awesome! 👍

Easy enough, right?

Next we will learn about

Matrix Transformation with Numpy

Matrix transformation means changing the form of a matrix to another form.

There are three functions used for matrix transformation:

  • transpose()to invert a matrix;
  • reshape()to change the shape of the matrix to a certain size;
  • flatten()and ravel()to convert a matrix into a list or vector.

Let's try it!

Practice: Transpose a Matrix with Numpy

Create a new file with the name balik_matrik.py, then fill it with the following code:

balik_matrik.py
import numpy as np

# membuat matrik
matrik_a = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

print("Matriks awal: ")
print(matrik_a)

# membalik matrik
hasil = matrik_a.transpose()

print("Matriks kebalikan: ")
print(hasil)

After that, try running it!

So the result is:

Transpose matrices in Numpy

Apart from using the technique above, we can also invert the matrix like this.

np.transpose(matrik_a)

# atau bisa juga

matrik_a.T # ini akan menghasilkan matriks hasil transpose

Practice: Changing the size of a Matrix

Create a new file with the name matrik_reshape.py, then fill it with the following code:

matrik_reshape.py
import numpy as np

# membuat matrik
matrik_a = np.array([1, 2, 3, 4, 5, 6])

print("Matriks awal: ")
print(matrik_a)
print("Ukuran = ", matrik_a.shape)

# mengubah ukuran ke 3x2
hasil = matrik_a.reshape(3, 2)

print("Mengubah ke 3x2: ")
print(hasil)
print("Ukuran = ", hasil.shape)

After that, try running it!

So the result is:

Reshape the matrix with Numpy

In this example, we convert a list into a 2x3 matrix. The attribute .shapefunctions to determine the size of the array.

We can also restore the matrix that we have reshaped with the function reshape().

Example:

np.reshape(matrik_a, 6)

The number 6is the size of the matrix.

Practice: Converting a Matrix to a List of Vectors

Create a new file with the name matrik_flat.py, then fill it with the following code:

matrik_flat.py
import numpy as np

# membuat matrik
matrik_a = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

print("Matriks awal: ")
print(matrik_a)
print("Ukuran = ", matrik_a.shape)

hasil = matrik_a.flatten()

print("Matriks setelah di-flatten: ")
print(hasil)
print("Ukuran = ", hasil.shape)

After that, try running it!

So the result is:

Flatten-matrix example

So far we can use Numpy to create lists and matrices.

Next we will try functions for data processing.

Data Processing Functions in Numpy

If you have ever studied statistics, you will probably be familiar with mean (average), sum, min, max, etc.

Well, in Numpy... we have provided these functions. So data processing will be easier.

Let's just try an example.

Create a new file with the name pengolahan_data.pythen fill it with the following code:

import numpy as np

nilai_siswa = np.array([55, 43, 98, 76 ,65 ,77 ,65, 90])
print("Nilai minimal = ", nilai_siswa.min())
print("Nilai maksimal = ", nilai_siswa.max())
print("Nilai rata-rata = ", nilai_siswa.mean())
print("Total nilai = ", nilai_siswa.sum())
print("Standar Deviasi = ", nilai_siswa.std())

After that try running it!

So the result is:

Example of coding statistical data in Python

Awesome! 👍

With these functions, our Data Science work will become easier.

What is next?

So far we understand and know what Numpy is and how to use it.

Actually, there are many more functions that we have not discussed. Of course it won't be enough if I discuss everything here.

Therefore, you can continue with your own exploration.

Try doing this in the Python shell:

>>> import numpy as np
>>> dir(np) # untuk ngeliat list semua fungsi di Numpy
>>> help(np) # untuk baca dokumentasi dan manual dari Numpy

Apart from that, you can also learn Numpy from its official documentation .

Happy learning!

Post a Comment

Previous Post Next Post