DEV Community

Cover image for NumPy (Part 1)
Crazy Codigo
Crazy Codigo

Posted on

NumPy (Part 1)

In coding, we often use arrays / tensors to represent data. One may think of these arrays as matrices. When we want to make sets of data interact with each other and come to results, we do the same thing that we would in Algebra - we perform operations on the matrices.

Now, we have already established that Python as a language exists only to make our lives easier. So obviously, there is a module in Python that lets us do all kinds of functions on our matrices: NumPy.

Read on to start off with NumPy.

Note: It is recommended that you know basic algebra and matrices in order to understand all the functions.

Importing the module

The first thing we need to do is install NumPy. The only pre-requisite to do this is having Python itself. Now, I personally use pip for installing modules. However, you may also use conda.

For pip run, the following in terminal -

pip install numpy
Enter fullscreen mode Exit fullscreen mode

If you are using conda, the command would be -

# If you want to install from conda-forge
conda config --env --add channels conda-forge

# The actual install command
conda install numpy
Enter fullscreen mode Exit fullscreen mode

After this, it is a simple import statement -

import numpy as np
Enter fullscreen mode Exit fullscreen mode

And there you go! You have imported NumPy module into your code.

Note: I have imported NumPy and given it the reference variable np to make it easier to run the functions. You may use any other variable name or skip it all together.

Creating Arrays

From this point on, I will be using IDLE Shell to run commands for the sake of simplicity.

To create the array, we use function array() from NumPy module.

arr = np.array([])
Enter fullscreen mode Exit fullscreen mode

Let's test it out by putting in some values and creating a 2X3 matrix -

arr = np.array([1,2,3] , [4,5,6])
Enter fullscreen mode Exit fullscreen mode

When we run this in shell, Python returns the matrix to us:
arr output

As you can see, we only put in the values. Python made the matrix for us on its own.

Indexing of Arrays

On many occasions we will be faced with situations where we would want to extract the elements of the array individually. For this, we need to understand how they are numbered or indexed.

Sticking to the example array we created (arr), the indexing would look like this -

So, if we want to get the element in the 0th row and 1st column, we would run -

Enter fullscreen mode Exit fullscreen mode

And it would give us 2.

We can also find out the dimensions of an array by executing:

Enter fullscreen mode Exit fullscreen mode

This will return a tuple with the syntax (rows, columns). In this case, it would be (2,3).

So, now you know how to install and import the module, create matrices and access elements in it. Follow the blog for part 2 coming very soon.

Top comments (0)