Exploring NumPy Functions

numpy Jun 22, 2019

Performing operations on arrays in NumPy


In the previous blog we learned about setting up the environment for python programming and how to install NumPy in PyCharm and IDLE. We also learned different ways of creating arrays in NumPy.

If you are new to this blog, please refer to the previous blog: Getting started with NumPy in Python

Lets start with a little introduction to NumPy. NumPy is a python array processing package and we can perform operations on one dimensional and multidimensional arrays with NumPy.

Lets first create two arrays for performing operations upon. We will use the methods that we learned in the previous blog.

Please make sure you are executing code on your own system along with reading this blog. It will help you get clear with the fundamentals.

  • Arithmetic Operations: Now, lets start by performing some arithmetic operations on the arrays we just created. Creating arrays with array() method. In the code below, we have created two 1 Dimensional arrays named arr1 and arr2.

Note that the arrays must be of same shape for performing arithmetic operations.

#importing the numpy package into our code 
import numpy as np 
#Lets create two arrays 
arr1 = np.array([1, 2, 3, 4, 5]) 
arr2 = np.array([9, 8, 7, 6, 5]) 
Creating arrays
#Lets perform addition on our arrays
add_arr = arr1 + arr2
print("Array after addition: ", add_arr)


Output: Array after addition: [10 10 10 10 10]
Performing addition on arrays

Yes, performing addition on arrays in Python is that easy... You can confirm this by executing it on your own system.

#Lets perform subtraction on our arrays
sub_arr = arr2 - arr1 
print("Array after subtraction: ", sub_arr)

#Lets perform Multiplication on our arrays 
mul_arr = arr1 * arr2 <br>
print("Array after multiplication: ", mul_arr)

#Lets perform division on our arrays 
div_arr = arr1 / arr2 
print("Array after division: ", div_arr)


Output: 
Array after subtraction: [8  6  4  2  0] 
Array after multiplication: [ 9  16  21  24  25]
Array after division: [9.          4.          2.33333333  1.5         1.        ] 
  • Sorting Operations: A variety of sorting related functions are inbuilt in NumPy. Each sorting functions implement different sorting algorithm. Now, we will perform sorting operations on our arrays. But first lets create a separate array.
  • Using sort() Method: In the code below, we can see that the output array is sorted. The syntax of sort() method is: numpy.sort(a, axis, kind, order) where:
  1. a: The array to be sorted
  2. axis: The axis along which the array is to be sorted. If not mentioned, the array is flattened.
  3. kind: The sorting algorithm to use, default is quicksort.
  4. order: If the array contains fields, the order of fields to be sorted.
#Importing numpy package into our code
import numpy as np
#Now lets create an array 
arr = np.array([98, 59, 34, 436, 4, 6, 123]) 
print("Array after sorting: ", np.sort(arr))


Output:
Array after sorting: [  4   6  34  59  98 123 436]
  • Using argsort() Method: In the code below, we can see that the output array is sorted. This method of sorting performs an indirect sorting on input array along the given axis and uses a specified kind of sort to return the array of indices of data. Then this array of indices is used to reconstruct the sorted array.
#importing numpy package into our code
import numpy as np
#Now lets create an array
arr = np.array([58, 45, 37, 23, 19, 90, 88, 79, 65, 54])
y = np.argsort(arr)	#This line of code sorts the indices of the input array
print("Sorted indices: ", y)
print("Array after sorting: ", arr[y])


Output:
Sorted indices: [4 3 2 1 9 0 8 7 6 5]
Array after sorting: [19 23 37 45 54 58 65 79 88 90]
  • Using nonzero() Method: In the code below, we can see that the output array consists of all the nonzero elements. And all the zero value elements are eliminated.
#importing numpy package into our code 
import numpy as np 
#now lets create an array 
arr = np.array([30, 40, 0, 20, 35, 80, 0, 0, 99]) 
#storing the indices of all nonzero elements in y 
y = np.nonzero(arr) 
#using the indices to recreate the array 
print("Nonzero elements: ", arr[y])


Output:
Nonzero elements: [30 40 20 35 80 99]
  • Using where() Method: In the code below we can see that the out put array consists of all the elements which are greater than 30. And all the elements which are less than 30 are eliminated.
#importing numpy package into our code
import numpy as np
#now lets create an array
arr = np.array([99, 109, 255, 78, 98, 10, 11, 34, 57, 54, 77])
#storing the indices of all elements >30 in y
y = np.where(arr > 30)
print("All the elements greater than 30: ", arr[y]) 


Output:
All the elements greater than 30: [ 99 109 255  78  98  34  57  54  77]
  • Using extract() Method: In the code below we can see that we have generated a condition 'y' which separates the elements which are completely divisible by 2. And then we store this value in a separate array 'y', which is further used to create the required array.
#importing the numpy package into our code
import numpy as np 
#now lets create an array
arr = np.array([78, 98, 434, 554, 232, 45, 66, 34, 23, 89, 00, 365]) 
#our condition 
y = np.mod(arr, 2) == 0
#printing the condition of each element 
print("Condition of each element: ", y) 
#printinfg the elements that satisfies the condition 
print("The elements that satisfies the condition 'y': ", np.extract(y, arr))


Output:
Condotion of each element: 
[ True  True  True  True  True False  True  True False False  True False]
The elements that satisfies the condition 'y': [ 78  98 434 554 232  66  34   0]
  • Array Manipulation: The NumPy Package provides us with some array manipulation functions also. We can use these array manipulation functions to alter our array. Some of the array manipulation functions are discussed below:
  • Using reshape() Method: We have used the reshape() method in the code below. The line of code y = arr.reshape(2, 6) converts the 1D array 'arr' into 2D array of size 2 x 6 and stores it in the variable 'y'.
#importing numpy package into our code 
import numpy as np 
#creating an array 
arr = np.array([78, 98, 434, 554, 232, 45, 66, 34, 23, 89, 00, 365]) 
print("Array before reshaping: ", arr) 
#using the reshape() Method 
y = arr.reshape(2, 6) 
print("Array after reshaping: \n", y) 


Output: 
Array before reshaping: [ 78  98 434 554 232  45  66  34  23  89   0 365]
Array after reshaping: 
[[ 78  98 434 554 232  45]
 [ 66  34  23  89   0 365]]
  • Using flatten() Method: We have used the flatten() method in the code below to convert the 2D array 'arr' into a 1D array.
#importing numpy into our code
import numpy as np
#creating an array
arr = np.array([[78, 98, 434, 554], [232, 45, 66, 34], [23, 89, 00, 365]])
print("Array before using flatten: \n", arr)
print("Array after using flatten: \n", arr.flatten())


Output:
Array before using flatten: 
[[ 78  98 434 554] 
 [232  45  66  34]
 [ 23  89   0 365]] 
Array after using flatten: 
[ 78  98 434 554 232  45  66  34  23  89   0 365] 
  • Using append() Method: The append() Method adds the specified element at the end of the array.
#importing numpy into our code
import numpy as np
#creating an array
arr = np.array([78, 98, 434, 554, 232, 45, 66, 34, 23, 89, 00, 365])
print("Array before appending: ", arr)
arr = np.append(arr, 333) 
print("Array after appending: ", arr) 


Output:
Array before appending: [ 78  98 434 554 232  45  66  34  23  89   0 365]
Array after appending: [ 78  98 434 554 232  45  66  34  23  89   0 365 333]

Aditya Kumar

A thinker, reader, developer and coffee maniac. I am an undergraduate student at UPES University, Dehradun.