30.numpy 3

NumPy Splitting Array

Splitting is reverse operation of Joining.
Joining merges multiple arrays into one and Splitting breaks one array into multiple.
We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.

Example

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)
>>> [array([1, 2]), array([3, 4]), array([5, 6])]

Note

"We also have the method split() available but it will not adjust the elements when elements are less in source array for splitting like in example above, array_split() worked properly but split() would fail."

The return value of the array_split() method is an array containing each of the split as an array.

Example

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)

print(newarr[0])
>>> [1 2]
print(newarr[1])
>>> [3 4]
print(newarr[2])
>>> [5 6]

Splitting 2-D Arrays

Split the 2-D array into three 2-D arrays.

import numpy as np

arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
newarr = np.array_split(arr, 3)

print(newarr)
>>> [array([[1, 2],
          [3, 4]]), array([[5, 6],
          [7, 8]]), array([[ 9, 10],
          [11, 12]])]

Split the 2-D array into three 2-D arrays along columns.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]])
newarr = np.array_split(arr, 3, axis=1)

print(newarr)
>>> [array([[ 1],
          [ 4],
          [ 7],
          [10],
          [13],
          [16]]), array([[ 2],
          [ 5],
          [ 8],
          [11],
          [14],
          [17]]), array([[ 3],
          [ 6],
          [ 9],
          [12],
          [15],
          [18]])]

NumPy Searching Arrays

You can search an array for a certain value, and return the indexes that get a match.

To search an array, use the where() method.

Example

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
print(x)
>>> (array([3, 5, 6]),)

Search Sorted

There is a method called searchsorted() which performs a binary search in the array, and returns the index where the specified value would be inserted to maintain the search order.

The searchsorted() method is assumed to be used on sorted arrays.

Example

import numpy as np

arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7)
print(x)
>>> 1

Search From the Right Side

By default the left most index is returned, but we can give side='right' to return the right most index instead.

Example

import numpy as np

arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7, side='right')
print(x)
>>> 2

The method starts the search from the right and returns the first index where the number 7 is no longer less than the next value.

Multiple Values

To search for more than one value, use an array with the specified values.

Example

import numpy as np

arr = np.array([1, 3, 5, 7])
x = np.searchsorted(arr, [2, 4, 6])

print(x)
>>> [1 2 3]

NumPy Sorting Arrays

Sorting means putting elements in a ordered sequence.
Ordered sequence is any sequence that has an order corresponding to elements, like numeric or alphabetical, ascending or descending.
The NumPy ndarray object has a function called sort(), that will sort a specified array.

Sort the Array

import numpy as np

arr = np.array([3, 2, 0, 1])
print(np.sort(arr))
>>> [0 1 2 3]

This method returns a copy of the array, leaving the original array unchanged.

Sort the array alphabetically

import numpy as np

arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr))
>>> ['apple' 'banana' 'cherry']

Sort a boolean array

import numpy as np

arr = np.array([True, False, True])
print(np.sort(arr))
>>> [False True True]

Sorting a 2-D Array

If you use the sort() method on a 2-D array, both arrays will be sorted

Sort a 2-D Array

import numpy as np

arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))
>>> [[2 3 4]
     [0 1 5]]

NumPy Filter Array

Getting some elements out of an existing array and creating a new array out of them is called filtering.

In NumPy, you filter an array using a boolean index list.
A boolean index list is a list of booleans corresponding to indexes in the array.

If the value at an index is True that element is contained in the filtered array, if the value at that index is False that element is excluded from the filtered array.

Example

import numpy as np

arr = np.array([41, 42, 43, 44])
x = [True, False, True, False]
newarr = arr[x]
print(newarr)
>>> [41 43]

The new filter contains only the values where the filter array had the value True, in this case, index 0 and 2.

Creating the Filter Array

In the example above we hard-coded the True and False values, but the common use is to create a filter array based on conditions.

Create a filter array that will return the values higher than 42

import numpy as np

arr = np.array([41, 42, 43, 44])

# Create an empty list
filter_arr = []

# go through each element in arr
for element in arr:
  # if the element is higher than 42, set the value to True, otherwise False:
  if element > 42:
    filter_arr.append(True)
  else:
    filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
>>> [False, False, True, True]
print(newarr)
>>> [43 44]

Creating Filter Directly From Array

We can directly substitute the array instead of the iterable variable in our condition and it will work just as we expect it to.

Create a filter array that will return the values higher than 42

import numpy as np

arr = np.array([41, 42, 43, 44])
filter_arr = arr > 42
newarr = arr[filter_arr]

print(filter_arr)
>>> [False False  True  True]
print(newarr)
>>> [43 44]

Create a filter array that will return only even elements from the original array

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])
filter_arr = arr % 2 == 0
newarr = arr[filter_arr]

print(filter_arr)
>>> [False  True False  True False  True False]
print(newarr)
>>> [2 4 6]

Random Numbers in NumPy

Random number does NOT mean a different number every time. Random means something that can not be predicted logically.

Generate Random Number

NumPy offers the random module to work with random numbers.

Generate a random integer from 0 to 100

from numpy import random
x = random.randint(100)
print(x)
>>> 98

Generate Random Float

The random module's rand() method returns a random float between 0 and 1

The random module's rand() method returns a random float between 0 and 1

from numpy import random
x = random.rand()
print(x)
>>> 0.4516533963530909

Generate Random Array

The randint() method takes a size parameter where you can specify the shape of an array.

Generate a 1-D Array

from numpy import random
x=random.randint(100, size=(5))
print(x)
>>> [23 22 74 44 50]

Generate a 2-D Array

from numpy import random
x = random.randint(100, size=(3, 5))
print(x)
>>> [[80 54 19 74 65] 
    [26 60 69 34 25] 
    [50 16 53 84 90]]

Floats

The rand() method also allows you to specify the shape of the array.

Generate a 1-D Array

from numpy import random
x = random.rand(5)
print(x)
>>> [0.6313987 0.7341789 0.0873221 0.0752967 0.2127466]

Generate a 2-D Array

from numpy import random
x = random.rand(3, 5)
print(x)
>>> [[0.03379952 0.78263517 0.9834899  0.47851523 0.02948659] 
    [0.36284007 0.10740884 0.58485016 0.20708396 0.00969559] 
    [0.88232193 0.86068608 0.75548749 0.61233486 0.06325663]]

Generate Random Number From Array

The choice() method allows you to generate a random value based on an array of values.
This method takes an array as a parameter and randomly returns one of the values.

Example

from numpy import random
x = random.choice([3, 5, 7, 9])
print(x)
>>> 5

The choice() method also allows you to return an array of values.
Add a size parameter to specify the shape of the array.

Example

from numpy import random
x = random.choice([3, 5, 7, 9], size=(3, 5))
print(x)
>>> [[9 3 5 5 7] 
    [7 5 3 3 9] 
    [7 5 9 9 7]]