Introduction

21

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.

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

`1 2 3`

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

python

**Output:**

`1`

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

`1 2`

`array3 = array1 + array2 array3`

python

**Output:**

`1`

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

`1 2`

`array4 = np.array([1,2,3,4]) array1 + 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.

`1`

`array1*2`

python

**Output:**

`1`

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

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

.

`1`

`array1**2`

python

**Output:**

`1`

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

`1`

`np.power(array1,3)`

python

**Output:**

`1`

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

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.

`1 2`

`array5 = array1 >= 30 array5`

python

**Output:**

`1`

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

`1`

`array1[array5]`

python

**Output:**

`1`

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

`1`

`array1[array1 >= 30]`

python

**Output:**

`1`

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

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

`1 2`

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

python

And print them:

`1`

`print(A)`

python

**Output:**

`1 2`

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

`1`

`print(B)`

python

**Output:**

`1 2`

`[[3 1] [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.

`1`

`A+B`

python

**Output:**

`1 2`

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

`1`

`A*B`

python

**Output:**

`1 2`

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

`1`

`A`

python

**Output:**

`1 2`

`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,

`1`

`A +=2`

python

**Output:**

`1 2`

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

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

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

`1`

`A @ B`

python

**Output:**

`1 2`

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

`1`

`A.dot(B)`

python

**Output:**

`1 2`

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

Next, let’s use the `random`

function to generate a two-dimensional array.

`1 2`

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

python

**Output:**

`1 2`

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

`1`

`array.sum()`

python

**Output:**

`1`

`1.5438454156151251`

The `min`

function finds the lowest value in the array.

`1`

`array.min()`

python

**Output:**

`1`

`0.08920266767965357`

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.

`1`

`array.sum(axis=0)`

python

**Output:**

`1`

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

`1`

`array.min(axis=1)`

python

**Output:**

`1`

`array([0.07580989, 0.1670734 ])`

Numpy provides logic functions like `logical_and`

, `logical_or`

etc., in a similar pattern to perform logical operations. For example:

`1`

`np.logical_and(True, True)`

python

**Output:**

`1`

`True`

`1`

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

python

**Output:**

`1`

`False`

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:

`1 2`

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

python

**Output:**

`1 2 3`

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

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

`1 2`

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

python

**Output:**

`1 2 3`

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

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.

21

Test your skills. Learn something new. Get help. Repeat.

Start a FREE 10-day trial