Introduction To Numpy

Introduction To Numpy

In this Blog, I will be writing about all the basic stuff you need to know about numpy .

  • What is NumPy?

    NumPy(Numerical Python) is a Python library used for working with arrays.

  • Why Use NumPy?

    In Python we have lists that serve the purpose of arrays, but they are slow to process. NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.The array object in NumPy is called ndarray.

    Numpy Arrays are very frequently used in data science.

  • Installing NumPy

    pip install numpy
    
  • Importing NumPy

    To import NumPy in your workspace
      import numpy as np
    
  1. Creating array using NumPy

    The array object in NumPy is called ndarray.

    We can create a NumPy ndarray object by using the array() function.

    Example :

      import numpy as np
      arr=np.array([2,4,6,8,10])
      print(arr)
      type(arr)
    

    type() - Built in python library which tells the type of object passed. Here it will show - numpy.ndarray

  2. NumPy Array Indexing

    You can access an array element by referring to its index number.

    The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

    Example - Access 2nd element of an array.

      import numpy as np
      arr=np.array([1,3,5,7])
      print(arr[1])
    
      #output -> 3
    
  3. Access 2-D Arrays

    To access elements from 2-D arrays we can use comma separated integers representing the dimension and the index of the element.

    Example - Access 4th element on 2nd dimension .

         import numpy as np
         arr=np.array([[1,2,3,4,5],[6,7,8,9]])
         print(‘4th element on 2nd dim: ‘, arr[1, 3])
    
         #output -> 9
    
  4. Array Slicing

    Slicing in python means taking elements from one given index to another given index.

    We pass slice instead of index like this: [start:end].

    Example - Access elements from index 2 to 5

         import numpy as np
         arr=np.array([1,2,3,4,5,6])
         print(arr[2:5])
    
         #output -> [3,4,5]
    
  5. NumPy Array Shape

    NumPy arrays have an attribute called shape that returns a tuple with each index having the number of corresponding elements.

    Example - Print shape of 2D Array-

       import numpy as np
    
       arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
    
       print(arr.shape)
    
       #output -> (2,4)
    

I tried to provide all the important information on numpy for beginners. I hope you will find something useful here. Happy Learning !!