NumPy Introduction

-Stands for Numerical Python

  • provides an array object that is faster than the common python array.

  • To install pip install numpy

  • After installing open your jupiter notebook or python file and type `import numpy`

Example 1:

convert and array to numpy array

import numpy as np

arr = [1,2,4,5]

arr = numpy.array(arr)

print(arr)

Example 2: Creating an array from tuple

import numpy as np

tuple1 = (1,3,5,6)

nparr_from_tupple = np.array(tuple1)

Example 3: 0-D Arrays

When an array has single elements like `42` we call it a one dimesional array

import numpy as np

oned = np.array(42)

print(oned)

Example 4: 1D-Arrays

If the array consists of multiple elements like [1, 4, 5, 6, 7, 8] in nupmy it it will be: array([1, 4, 5, 6, 7, 8]) ,then the array is 1D

import numpy as np

nparr = np.array([1,4,5,6,7])

print(nparr)

Example 5: 2-D Arrays

If the array elements has other arrays as its elemets which are 1-D, then its is 2D

import numpy as np

arr= [[1,2],[3,4]]

nparr = np.array(arr)

Example 6: Summary

one_D = np.array(42) #one D
two_D  = np.array([1, 2, 3, 4, 5]) #2D
three_D   = np.array([[1, 2, 3], [4, 5, 6]]) #3D
four_D   = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]) #4D

Example 7: Defining dimensions with ndmin

To do that we use ndmin argument

import numpy as np

arr = np.array([1,2,4], ndim=5)
arr = np.array([1,2,4], ndmin=2)
print(arr)

Example 8: Accessing Numpy array Elements

You can do so by using an index eg

import numpy as np
arr = [1,2,3]

print(arr[0])
print(arr[1])
print(arr[2])

Example 9: Access 2-D Arrays

-use comma separated integers. Since its like rows and colums it will ideally be like [row,column]

The same also applies to 3D arrays you can access them like arr[1,1,0] or arr[0,0,1]


import numpy as np

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


arr[0,0] # 1
arr[1,0] #1

Example 10: Negative Indexing

To access array from the end, use negative indexes

import numpy as np

arr2 = np.array([[1,2,3,4,5,6,7], [1,2,3,4,5,6,10]])


arr[0,-1] # 7
arr[1,-2] #10

Example 11: Slicing Arrays

# syntax [start:end] or [start:end:step]
#NOTE:result includes the start index, but excludes the end index.
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5]) # prints form 1-4, [2,3,4,5]
arr[1:] # from index 1 to the end
arr[:3] # START FROM 0 to index 2 (dont include 3)

arr[-4:-1] #[4,5,6] will not inlude the end index value

Example 12: Slicing 2-D Arrays

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
arr[1, 1:4] # in row 1 return 1 to 3 [6,7,8]
arr[0:, 2] # return second element in each row

Example 13: Iterating using nditer()

import numpy as np

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

for x in np.nditer(arr):
  print(x) # 1,2,3,4,5,6,7,8

Well, that the commonly used numpy concept for now. Thank you and see you soon.