 Ravikiran Srinivasulu

# Overview of Basic Numpy Operations

• Sep 25, 2018
• 65,994 Views
• Sep 25, 2018
• 65,994 Views
Python
Numpy

## Introduction

Once you have created the arrays, you can do basic Numpy operations. This guide will provide you with a set of tools that you can use to manipulate the arrays. If you would like to know the different techniques to create an array, refer to my previous guide: Different Ways to Create Numpy Arrays.

## Operations on a 1d Array

### Using Arithmetic Operators with Numpy

Let’s look at a one-dimensional array. I have 2 arrays, array1 and array2, created through two different techniques:

``````1array1 = np.array([10,20,30,40,50])
2array2 = np.arange(5)
3array2
``````
python

Output:

``1array([0, 1, 2, 3, 4])``

You can perform arithmetic operations on these arrays. For example, if you add the arrays, the arithmetic operator will work element-wise. The output will be an array of the same dimension.

``````1array3 = array1 + array2
2array3
``````
python

Output:

``1array([10, 21, 32, 43, 54])``

Here is a pictorial representation of the same: If you try to add arrays with the same dimension but a different number of elements, you will get an error. For example:

``````1array4 = np.array([1,2,3,4])
2array1 + array4``````
python

Output:

``1**ValueError**: operands could not be broadcast together with shapes (5,) (4,)``

You can run an arithmetic operation on the array with a scalar value. For example, this code multiplies each element of the array by 2.

``1array1*2``
python

Output:

``1array([ 20,  40,  60,  80, 100])``

To find the square of the numbers, use `**`.

``1array1**2``
python

Output:

``1array([ 100,  400,  900, 1600, 2500], dtype=int32)``

If you would like to cube the individual elements, or even higher up, use the `power` function. Here, each element of the array is raised to the power 3.

``1np.power(array1,3)``
python

Output:

``1array([  1000,   8000,  27000,  64000, 125000], dtype=int32)``

### Using Numpy with Conditional Expressions

You can use conditionals to find the values that match your criteria. Since array1 is an array, the result of a conditional operation is also an array. When we perform a conditional check, the output is an array of booleans.

``````1array5 = array1 >= 30
2array5
``````
python

Output:

``1array([False, False,  True,  True,  True])``

You can also pass this array of booleans to the main array to fetch the values that match criteria.

``1array1[array5]``
python

Output:

``1array([30, 40, 50])``

Rather than creating a separate array of booleans, you can specify the conditional operation directly on the main array. Something like this:

``1array1[array1 >= 30]``
python

Output:

``1array([30, 40, 50])``

This is a simple one-step process. First, the conditional operation is evaluated and then the results of the conditional operation are passed to the main array to get the filtered results.

## Operations on a 2D Array

### Arithmetic Operators with Numpy 2D Arrays

Let’s create 2 two-dimensional arrays, A and B.

``````1A = np.array([[3,2],[0,1]])
2B = np.array([[3,1],[2,1]])``````
python

And print them:

``1print(A)``
python

Output:

``````1[[3 2]
2 [0 1]]
``````
``1print(B)``
python

Output:

``````1[[3 1]
2 [2 1]]
``````

Note: if you print the arrays, you will not get the `array` keyword in the output.

Now, let’s try adding the arrays. Unsurprisingly, the elements at the respective positions in arrays are added together.

``1A+B``
python

Output:

``````1array([[6, 3],
2          [2, 2]])
``````

Here is the pictorial representation. All the arithmetic operations work in a similar way. You can also multiply or divide the arrays. The operations are performed element-wise.

``1A*B``
python

Output:

``````1array([[9, 2],
2          [0, 1]])
``````

Similar to programming languages like C# and Java, you can also use operators like +=, *= on your Numpy arrays. For example, we have the array:

``1A``
python

Output:

``````1array([[3, 2],
2       [0, 1]])
``````

Doing += operation on the array ‘A’ is equivalent to adding each element of the array with a specified value. So,

``1A +=2``
python

Output:

``````1array([[5, 4],
2       [2, 3]])
``````

Note that this operation is performed in place. Similarly, you can use other arithmetic operations like -= and\ *=.

### Matrix Multiplication

To perform a typical matrix multiplication (or matrix product), you can use the operator ‘@.’

``1A @ B``
python

Output:

``````1array([[13,  5],
2       [ 2,  1]])
``````

This is how it works: the cell (1,1) (value: 13) in the output is a Sum-Product of Row 1 in matrix A (a two-dimensional array A) and Column 1 in matrix B.

Similarly, the cell (1,2) in the output is a Sum-Product of Row 1 in matrix A and Column 2 in matrix B.

And so on, the values are populated for all the cells.

Here is a pictorial representation for cell (1,1): The same output can also be achieved by the function `dot`. For example:

``1A.dot(B)``
python

Output:

``````1array([[13,  5],
2       [ 2,  1]])
``````

### Arithmetic Functions in Numpy

Next, let’s use the `random` function to generate a two-dimensional array.

``````1array = np.random.random((2,2))
2array
``````
python

Output:

``````1array([[0.33260853, 0.07580989],
2       [0.96835359, 0.1670734 ]])
``````

There are several functions that you can use to perform arithmetic operations on this array. For example, the `sum` function adds all the values in the array and gives a scalar output.

``1array.sum()``
python

Output:

``11.5438454156151251``

The `min` function finds the lowest value in the array.

``1array.min()``
python

Output:

``10.08920266767965357``

### Using Axis Parameter

If you have more than one dimension in your array, you can define the axis; along which, the arithmetic operations should take place.

For example, for a two-dimensional array, you have two axes. Axis 0 is running vertically downwards across the rows, while Axis 1 is running horizontally from left to right across the columns. If you want the sum of all the values in a single column, use the Axis parameter with value ‘0.’ The first value in the resulting array represents the sum of all values in the first column and the second value represents the sum of all values in the second column.

``1array.sum(axis=0)``
python

Output:

``1array([1.30096212, 0.24288329])``

Similarly, to find the lowest value across a particular row, use the Axis parameter with a Value ‘1.’ Each of the values in the resulting array represents the lowest value for that particular row.

``1array.min(axis=1)``
python

Output:

``1array([0.07580989, 0.1670734 ])``

### Logical Operators in Numpy

Numpy provides logic functions like `logical_and`, `logical_or` etc., in a similar pattern to perform logical operations. For example:

``1np.logical_and(True, True)``
python

Output:

``1True``
``1np.logical_or(5>6,0>1)``
python

Output:

``1False``

### Other Functions in Numpy

In addition to arithmetic operators, Numpy also provides functions to perform arithmetic operations. You can use functions like `add`, `subtract`, `multiply`, `divide` to perform array operations. For example:

``````1a = np.arange(9).reshape(3,3)
2a
``````
python

Output:

``````1array([[0, 1, 2],
2       [3, 4, 5],
3       [6, 7, 8]])
``````

Let’s add a one-dimensional array to the two-dimensional array.

``````1b = np.array([2,4,6])
python

Output:

``````1array([[ 2,  5,  8],
2       [ 5,  8, 11],
3       [ 8, 11, 14]])
``````

Note that, array ‘b’ is added to each row in the array ‘a.’ So the array dimensions should match.

## Conclusion

This guide provides you with several tools that you can use to manipulate arrays. Most of the examples that are covered are for one-dimensional and two-dimensional arrays. They work the same and you can apply them to several higher dimensions where you’ll notice, they work like a gem.