Skip to main content

NumPY In python

 NumPy Stands for numerical python

How do I install NumPy?

To install Python NumPy, go to your command prompt and type “pip install numpy”.

 Once the installation is completed, go to your IDE (For example: PyCharm) and simply import it by typing: 

“import numpy as np”





Here, I have different elements that are stored in their respective memory locations. It is said to be two dimensional because it has rows as well as columns. In the above image, we have 3 columns and 4 rows available.

How do I start NumPy?

Single-dimensional Numpy Array:

1
2
3
import numpy as np
a=np.array([1,2,3])
print(a)

Output – [1 2 3]

Multi-dimensional Array:

1
2
a=np.array([(1,2,3),(4,5,6)])
print(a)

O/P – [[ 1 2 3]
[4 5 6]]


Python NumPy Array v/s List

Why NumPy is used in Python?

We use python NumPy array instead of a list because of the below three reasons:

  1. Less Memory
  2. Fast
  3. Convenient

The very first reason to choose python NumPy array is that it occupies less memory as compared to list. 

Then, it is pretty fast in terms of execution and at the same time, it is very convenient to work with NumPy. 

Python NumPy Operations:

  • NumpyArray - python numpy tutorial - Edurekandim:
    You can find the dimension of the array, whether it is a two-dimensional array or a single dimensional array. So, let us see this practically how we can find the dimensions. In the below code, with the help of ‘ndim’ function, I can find whether the array is of single dimension or multi dimension.
1
2
3
import numpy as np
a = np.array([(1,2,3),(4,5,6)])
print(a.ndim)

Output – 2

Since the output is 2, it is a two-dimensional array (multi dimension).

  • NumpyByte - python numpy tutorial - Edurekaitemsize:
    You can calculate the byte size of each element. In the below code, I have defined a single dimensional array and with the help of ‘itemsize’ function, we can find the size of each element.
1
2
3
import numpy as np
a = np.array([(1,2,3)])
print(a.itemsize)

Output – 4

So every element occupies 4 byte in the above numpy array.

  • Datatype - python numpy tutorial - Edurekadtype:
    You can find the data type of the elements that are stored in an array. So, if you want to know the data type of a particular element, you can use ‘dtype’ function which will print the datatype along with the size. In the below code, I have defined an array where I have used the same function.

 

1
2
3
import numpy as np
a = np.array([(1,2,3)])
print(a.dtype)

Output – int32

1
2
3
4
import numpy as np
a = np.array([(1,2,3,4,5,6)])
print(a.size)
print(a.shape)

Output – 6 (1,6)


  • reshape:
    Reshape is when you change the number of rows and columns which gives a new view to an object. Now, let us take an example to reshape the below array:

    As you can see in the above image, we have 3 columns and 2 rows which has converted into 2 columns and 3 rows. Let me show you practically how it’s done.

    1
    2
    3
    4
    5
    import numpy as np
    a = np.array([(8,9,10),(11,12,13)])
    print(a)
    a=a.reshape(3,2)
    print(a)

    Output – [[ 8 9 10] [11 12 13]] [[ 8 9] [10 11] [12 13]]




  • slicing:


    Before getting into the above example, let’s see a simple one. We have an array and we need a particular element (say 3) out of a given array. Let’s consider the below example:

    1
    2
    3
    import numpy as np
    a=np.array([(1,2,3,4),(3,4,5,6)])
    print(a[0,2])

    Output – 3

    Here, the array(1,2,3,4) is your index 0 and (3,4,5,6) is index 1 of the python numpy array. Therefore, we have printed the second element from the zeroth index.
    Taking one step forward, let’s say we need the 2nd element from the zeroth and first index of the array. Let’s see how you can perform this operation:

    1
    2
    3
    import numpy as np
    a=np.array([(1,2,3,4),(3,4,5,6)])
    print(a[0:,2])

    Output – [3 5]

    Here colon represents all the rows, including zero. Now to get the 2nd element, we’ll call index 2 from both of the rows which gives us the value 3 and 5 respectively.

    Next, just to remove the confusion, let’s say we have one more row and we don’t want to get its 2nd element printed just as the image above. What we can do in such case?
    Consider the below code:

    1
    2
    3
    import numpy as np
    a=np.array([(8,9),(10,11),(12,13)])
    print(a[0:2,1])

    Output – [9 11]

    As you can see in the above code, only 9 and 11 gets printed. Now when I have written 0:2, this does not include the second index of the third row of an array. Therefore, only 9 and 11 gets printed else you will get all the elements i.e [9 11 13].


Flatten

This function returns a copy of an array collapsed into one dimension. The function takes the following parameters.

ndarray.flatten(order)
import numpy as np 
a = np.arange(8).reshape(2,4) 

print 'The original array is:' 
print a 
print '\n'  
# default is column-major 

print 'The flattened array is:' 
print a.flatten() 
print '\n'  

print 'The flattened array in F-style ordering:' 
print a.flatten(order = 'F')

The output of the above program would be as follows −

The original array is:
[[0 1 2 3]
 [4 5 6 7]]

The flattened array is:
[0 1 2 3 4 5 6 7]

The flattened array in F-style ordering:
[0 4 1 5 2 6 3 7]


NumPy – Broadcasting

The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed.

Example 1

import numpy as np 

a = np.array([1,2,3,4]) 

b = np.array([10,20,30,40]) 

c = a * b 

print c

Its output is as follows −[10   40   90   160]

If the dimensions of the two arrays are dissimilar, element-to-element operations are not possible. However, operations on arrays of non-similar shapes is still possible in NumPy, because of the broadcasting capability. The smaller array is broadcast to the size of the larger array so that they have compatible shapes.

Broadcasting is possible if the following rules are satisfied −

  • Array with smaller ndim than the other is prepended with ‘1’ in its shape.
  • Size in each dimension of the output shape is maximum of the input sizes in that dimension.
  • An input can be used in calculation if its size in a particular dimension matches the output size or its value is exactly 1.
  • If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.

A set of arrays is said to be broadcastable if the above rules produce a valid result and one of the following is true −

  • Arrays have exactly the same shape.
  • Arrays have the same number of dimensions and the length of each dimension is either a common length or 1.
  • Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true.

The following figure demonstrates how array b is broadcast to become compatible with a.

















Comments

Popular posts from this blog

Is-A and Has-A relationships in python

  In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House. #Is-A relationship --> By Inheritance class  A:    def   __init__ ( self ):      self .b= 10    def   mym1 ( self ):      print ( 'Parent method' ) class  B(A):    def   mym2 ( self ):      print ( 'Child method' ) d = B() d.mym1() #output: Parent method d.mym2() #output: Child method HAS-A Relationship:  Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom. Let’s understand...

Magic Methods in Python

  What Are Dunder Methods ? In Python, special methods are a set of predefined methods you can use to enrich your classes.  They are easy to recognize because they start and end with double underscores, for example  __init__  or  __str__ . Dunder methods let you emulate the behavior of built-in types.  For example, to get the length of a string you can call  len('string') . But an empty class definition doesn’t support this behavior out of the box: These “dunders” or “special methods” in Python are also sometimes called “magic methods.” class NoLenSupport : pass >>> obj = NoLenSupport () >>> len ( obj ) TypeError : "object of type 'NoLenSupport' has no len()" To fix this, you can add a  __len__  dunder method to your class: class LenSupport : def __len__ ( self ): return 42 >>> obj = LenSupport () >>> len ( obj ) 42 Object Initialization:  __init__ "__init __ ...

Inheritance and Types in Python

  Inheritance   Creating a new class from existing class is known as inheritance . The class from which features are inherited is known as base class and the class into which features are derived into is called derived class . Syntax: class  derived- class (base  class ):       < class -suite>      Inheritance promotes reusability of code by reusing already existing classes.  Inheritance is used to implement  is-a  relationship between classes.   Following hierarchy is an example representing inheritance between classes:   Single inheritance   When a derived class inherits only from syntax, the base class is called single inheritance. If it has one base class and one derived class it is called single inheritance.   Diagram     Syntax class  A:  #parent class         #some code       class  b(A):...