# Overview of Basic Numpy Operations

Sep 25, 2018 • 8 Minute Read

## 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:

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

**Output:**

` ``array([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.

` ````
array3 = array1 + array2
array3
```

**Output:**

` ``array([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:

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

**Output:**

` ``**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.

` ``array1*2`

**Output:**

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

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

` ``array1**2`

**Output:**

` ``array([ 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.

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

**Output:**

` ``array([ 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.

` ````
array5 = array1 >= 30
array5
```

**Output:**

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

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

` ``array1[array5]`

**Output:**

` ``array([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:

` ``array1[array1 >= 30]`

**Output:**

` ``array([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.

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

And print them:

` ``print(A)`

**Output:**

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

` ``print(B)`

**Output:**

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

Note: if you print the arrays, you will not get the

arraykeyword in the output.

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

` ``A+B`

**Output:**

` ````
array([[6, 3],
[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.

` ``A*B`

**Output:**

` ````
array([[9, 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:

` ``A`

**Output:**

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

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

` ``A +=2`

**Output:**

` ````
array([[5, 4],
[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 ‘@.’

` ``A @ B`

**Output:**

` ````
array([[13, 5],
[ 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:

` ``A.dot(B)`

**Output:**

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

### Arithmetic Functions in Numpy

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

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

**Output:**

` ````
array([[0.33260853, 0.07580989],
[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.

` ``array.sum()`

**Output:**

` ``1.5438454156151251`

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

` ``array.min()`

**Output:**

` ``0.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.

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

**Output:**

` ``array([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.

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

**Output:**

` ``array([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:

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

**Output:**

` ``True`

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

**Output:**

### 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:

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

**Output:**

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

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

` ````
b = np.array([2,4,6])
np.add(a,b)
```

**Output:**

` ````
array([[ 2, 5, 8],
[ 5, 8, 11],
[ 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.