Python

Program to Convert Gray Code to Binary

Python Program to Convert Gray Code to Binary

Although binary numbers are the most common way to store numbers, they can be challenging to use in many situations, necessitating the usage of a binary number variant. This is where Gray codes come in handy.

Gray code has the property that two consecutive numbers differ in just one bit. Because of this quality, grey code cycles through multiple states with low effort and is used in K-maps, error correction, communication, and so on.

Gray Code is a type of minimum-change coding in which the two subsequent values differ by only one bit. More specifically, it is a binary number system in which only a single bit varies while travelling from one step to the next.

We will learn how to convert gray to binary code in Python in this tutorial. A binary number is a number written in the base-2 numeral system. As a result, a binary number is made up of only 0s and 1s. So, today, we’ll learn how to represent binary and gray code numbers, how to convert a gray number to binary code, and how to use a Python program to convert a gray number to binary code.

Examples:

Example1:

Input:

given gray code =1001000010

Output:

The Binary string of the given gray code= 1001000010 is 1110000011

Example2:

Input:

given gray code =1000111100110

Output:

The Binary string of the given gray code= 1000111100110 is 1111010111011

Program to Convert Gray Code to Binary in Python

Below are the ways to convert the given gray code to binary number in python:

Method #1:Using Right Shift Operator and  While loop( Static Input)

Approach:

  • Give the binary number as static.
  • The grayToBin has been defined.
  • It accepts as an argument the Gray codeword string.
  • It returns the binary number connected with it as a string.
  • If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in the corresponding binary number, where the 0th bit is the MSB, g(0) = b(0) and b(i) = g(i) XOR b(i – 1) for I > 0.
  • Based on the preceding, b(i) = g(i) XOR g(i – 1) XOR… XOR g (0).
  • Thus, a Gray codeword g can be translated to its corresponding binary number by doing (g XOR (g >> 1) XOR (g >> 2) XOR… XOR (g >> m)), where m is such that g >> (m + 1) equals 0.

Below is the implementation:

# function which accepts the gray code  and returns the binary code  of the gray code
def grayToBin(grayCde):
   # Converting the given gray code to integer
    graynum = int(grayCde, 2)
   # Taking a temporary variable which stores the the gray code integer number
    tempnum = graynum
    # using while loop
    while tempnum != 0:
        tempnum >>= 1
        graynum ^= tempnum

        # bin(n) returns n's binary representation with the prefix '0b' removed
        # the slice operation removes the prefix.
    return bin(graynum)[2:]


# given gray code as static
graycode = "1001000010"
# passing this graycode to grayToBin function
resultbin = grayToBin(graycode)
print('The Binary string of the given gray code=', graycode, 'is', resultbin)

Output:

The Binary string of the given gray code= 1001000010 is 1110000011

Method #2:Using Right Shift Operator and  While loop( User Input)

Approach:

  • Scan the gray code string using input() function.
  • The grayToBin has been defined.
  • It accepts as an argument the Gray codeword string.
  • It returns the binary number connected with it as a string.
  • If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in the corresponding binary number, where the 0th bit is the MSB, g(0) = b(0) and b(i) = g(i) XOR b(i – 1) for I > 0.
  • Based on the preceding, b(i) = g(i) XOR g(i – 1) XOR… XOR g (0).
  • Thus, a Gray codeword g can be translated to its corresponding binary number by doing (g XOR (g >> 1) XOR (g >> 2) XOR… XOR (g >> m)), where m is such that g >> (m + 1) equals 0.

Below is the implementation:

# function which accepts the gray code  and returns the binary code  of the gray code
def grayToBin(grayCde):
   # Converting the given gray code to integer
    graynum = int(grayCde, 2)
   # Taking a temporary variable which stores the the gray code integer number
    tempnum = graynum
    # using while loop
    while tempnum != 0:
        tempnum >>= 1
        graynum ^= tempnum

        # bin(n) returns n's binary representation with the prefix '0b' removed
        # the slice operation removes the prefix.
    return bin(graynum)[2:]


# given gray code as static
graycode = input("Enter some random gray code string = ")
# passing this graycode to grayToBin function
resultbin = grayToBin(graycode)
print('The Binary string of the given gray code=', graycode, 'is', resultbin)

Output:

Enter some random gray code string = 1000111100110
The Binary string of the given gray code= 1000111100110 is 1111010111011

Related Programs:

Python Program to Convert Gray Code to Binary Read More »

Program to Read Height in Centimeters and then Convert the Height to Feet and Inches

Python Program to Read Height in Centimeters and then Convert the Height to Feet and Inches

Given height in centimeters , the task is to convert the given height to feet and inches in Python.

Examples:

Example1:

Input:

Enter some random height in centimeters = 179.5

Output:

The given height 179.5 cm in inches = 70.72 inches
The given height 179.5 cm in feet = 5.89 feet

Example2:

Input:

Enter some random height in centimeters = 165

Output:

The given height 165.0 cm in inches = 65.01 inches
The given height 165.0 cm in feet = 5.41 feet

Program to Read Height in Centimeters and then Convert the Height to Feet and Inches in Python

There are several ways to read height in centimeters and then convert it to feet and inches in  Python some of them are:

Method #1:Python Static Input

  • Give the height in centimeters as static input.
  • Convert the given height in centimeters to feet by multiplying it with 0.0328 and store it in a variable.
  • Convert the given height in centimeters to inches by multiplying it with 0.0.394 and store it in a variable.
  • Print the height in feet and inches.
  • Exit of Program.

Below is the implementation:

# Give the height in centimeters as static input.
heightcm = 165
# Convert the given height in centimeters to feet by multiplying it with 0.0328
# and store it in a variable.
heightfeet = 0.0328*heightcm
# Convert the given height in centimeters to inches by multiplying it with 0.0.394
# and store it in a variable.
heightinches = 0.394*heightcm
# Print the height in feet and inches.
print("The given height", heightcm, 'cm',
      'in inches = ', round(heightinches, 2), 'inches')
print("The given height", heightcm, 'cm',
      'in feet = ', round(heightfeet, 2), 'feet')

Output:

The given height 165 cm in inches =  65.01 inches
The given height 165 cm in feet =  5.41 feet

Explanation:

  • Given the height in centimeters as static input.
  • The height in centimeters is multiplied by 0.394 and saved in a new variable called height in inches.
  • The height in centimeters is multiplied by 0.0328 and saved in a new variable called height in feet.
  • It is printed the conversion height in inches and feet.

Method #2:Python User Input

Approach:

  • Enter the height in centimeters as user input using float(input()) function .
  • Convert the given height in centimeters to feet by multiplying it with 0.0328 and store it in a variable.
  • Convert the given height in centimeters to inches by multiplying it with 0.0.394 and store it in a variable.
  • Print the height in feet and inches.
  • Exit of Program.

Below is the implementation:

# Enter the height in centimeters as user input using int(input()) function.
heightcm = int(input('Enter some random height in centimeters = '))
# Convert the given height in centimeters to feet by multiplying it with 0.0328
# and store it in a variable.
heightfeet = 0.0328*heightcm
# Convert the given height in centimeters to inches by multiplying it with 0.0.394
# and store it in a variable.
heightinches = 0.394*heightcma
# Print the height in feet and inches.
print("The given height", heightcm, 'cm',
      'in inches = ', round(heightinches, 2), 'inches')
print("The given height", heightcm, 'cm',
      'in feet = ', round(heightfeet, 2), 'feet')

Output:

Enter some random height in centimeters = 169
The given height 169 cm in inches = 66.59 inches
The given height 169 cm in feet = 5.54 feet

Explanation:

  • As the height can be in decimals we take input using  float(input()) function.
  • The height in centimeters is multiplied by 0.394 and saved in a new variable called height in inches.
  • The height in centimeters is multiplied by 0.0328 and saved in a new variable called height in feet.
  • It is printed the conversion height in inches and feet.

Related Programs:

Python Program to Read Height in Centimeters and then Convert the Height to Feet and Inches Read More »

What’s placement new operator and why do we need it ?

Placement new operator and it’s need

This article is all about placement new operator.

Placement new operator :

placement new operator we use to pass a memory address to new as a parameter. This memory is used by the placement new operator to create the object and also to call the constructor on it and then returning the same passed address.

Need of placement new operator :

As we know when we create any object using new operator, then the memory is allocated on the heap.

int * ptr = new int;

But, while working sometimes we need to create an object dynamically for which some specific memory location will be allocated.

For example, we do not want new memory to be allocated on heap rather it needs to be allocated on a given memory address. Actually this scenario comes when we work on any embedded product or with shared memory. So, for this requirement we use placement new operator.

Below is an example code to achieve this :

// Program

#include <iostream>
#include <cstdlib>
#include <new>

int main()
{
// Here memory will not be allocated on heap.
int * space = new int[1004];
// It will use passed spacer to allocate the memory
int * ptr = new(space) int;
*ptr = 7;
std::cout<<(*ptr)<<std::endl;
delete [] buffer;
return 0;
}

What’s placement new operator and why do we need it ? Read More »

Program to Convert Binary to Gray Code

Python Program to Convert Binary to Gray Code

Although binary numbers are the most common way to store numbers, they can be challenging to use in many situations, necessitating the usage of a binary number variant. This is where Gray codes come in handy.

Gray code has the property that two consecutive numbers differ in just one bit. Because of this quality, grey code cycles through multiple states with low effort and is used in K-maps, error correction, communication, and so on.

We will learn how to convert binary to grey code in Python in this tutorial. A binary number is a number written in the base-2 numeral system. As a result, a binary number is made up of only 0s and 1s. So, today, we’ll learn how to represent binary and grey code numbers, how to convert a binary number to grey code, and how to use a Python program to convert a binary number to grey code.

Examples:

Example1:

Input:

binary String = "1010110101"

Output:

The Gray Code of the binary string= 1010110101 = 1111101111

Example2:

Input:

binary string = "110001101010"

Output:

The Gray Code of the binary string= 110001101010 = 101001011111

Program to Convert Binary to Gray Code in Python

Below are the ways to convert the given binary number to gray code in python:

Method #1:Using Right shift operator and Xor (Static Input)

Approach:

  • Give the binary number as static.
  • The function binToGray is created.
  • As an argument, it accepts a binary number as a string.
  • It returns the string corresponding to its Gray codeword.
  • If b(i) is the ith bit in the binary number and g(i) is the ith bit in the associated Gray codeword, where the 0th bit is the MSB, g(0) = b(0) and g(i) = b(i) XOR b(i – 1) for I > 0.
  • Thus, b XOR (b >> 1) can be used to convert a binary number b to its corresponding Gray codeword.
  • Exit of Program.

Below is the implementation:

# function which accepts the binary string and returns the gray code of the binary string
def binToString(binStr):
    # Converting the given binary string to integer
    binStr = int(binStr, 2)
    binStr ^= (binStr >> 1)

    # Returning the binary converted string using bin() function
    return bin(binStr)[2:]


# given binary number as static
binString = "1010110101"
# passing this binString to binToString function
resultGray = binToString(binString)
print('The Gray Code of the binary string=', binString, '=', resultGray)

Output:

The Gray Code of the binary string= 1010110101 = 1111101111

Method #2:Using Right shift operator and Xor (User Input)

Approach:

  • Scan the binary string using input() function.
  • The function binToGray is created.
  • As an argument, it accepts a binary number as a string.
  • It returns the string corresponding to its Gray codeword.
  • If b(i) is the ith bit in the binary number and g(i) is the ith bit in the associated Gray codeword, where the 0th bit is the MSB, g(0) = b(0) and g(i) = b(i) XOR b(i – 1) for I > 0.
  • Thus, b XOR (b >> 1) can be used to convert a binary number b to its corresponding Gray codeword.
  • Exit of Program.

Below is the implementation:

# function which accepts the binary string and returns the gray code of the binary string
def binToString(binStr):
    # Converting the given binary string to integer
    binStr = int(binStr, 2)
    binStr ^= (binStr >> 1)

    # Returning the binary converted string using bin() function
    return bin(binStr)[2:]


# given binary number as static
binString = input("Enter some random binary string = ")
# passing this binString to binToString function
resultGray = binToString(binString)
print('The Gray Code of the binary string=', binString, '=', resultGray)

Output:

Enter some random binary string = 11100010100101
The Gray Code of the binary string= 11100010100101 = 10010011110111

Related Programs:

Python Program to Convert Binary to Gray Code Read More »

Python Interview Questions

Python Interview Questions and Answers for Freshers & Experienced

Python is a vast subject and if you have to prepare for an interview in a short span of time you may feel a bit lost or overwhelmed about how to go about preparing for the day. Not to worry at all as BTech Geeks have come up with the best collection of commonly asked & basic Python Interview Questions for Freshers & Experienced candidates in this tutorial.

We all know that Programming language interviews can be tricky and so having strong foundations is very important. A technical interview starts as a simple discussion and then you would be asked questions randomly from different topics of python. The best way to prepare for such an interview is to follow a systematic approach and practice more with these basic to advanced concepts of Python Programming Interview Questions for Beginners.

Also Check: 

Python Programming Interview Questions and Answers for Freshers & Experienced

Here is the topic-wise list of Python Interview Questions for Freshers & Expert developers that helps you all to prepare well for a number of interviews in top companies. Take a look at them and press the pdf links for better preparation in no time.

Basic Python Interview Questions for Freshers

  1. What are the key features of Python?
  2. Differentiate between lists and tuples.
  3. Explain the ternary operator in Python.
  4. What are negative indices?
  5. How long can an identifier be in Python?
  6. What is the pass statement in Python?
  7. Is Python case-sensitive?
  8. How would you convert a string into lowercase?
  9. Explain help() and dir() functions in Python.
  10. How do you get a list of all the keys in a dictionary?
  11. How will you check if all characters in a string are alphanumeric?
  12. How would you declare a comment in Python?
  13. What is PEP 8?
  14. What are Python decorators?
  15. How is Python interpreted?

Frequently Asked Python Programming Interview Questions for Beginners

  1. What is Python good for?
  2. What is the Python interpreter prompt?
  3. How will you capitalize the first letter of a string?
  4. With Python, how do you find out which directory you are currently in?
  5. How do you insert an object at a given index in Python?
  6. How does a function return values?
  7. Will the do-while loop work if you don’t end it with a semicolon?
  8. Why do we need break and continue in Python?
  9. Can you name ten built-in functions in Python and explain each in brief?
  10. How will you convert a list into a string?
  11. Can you explain the life cycle of a thread?
  12. What is a dictionary in Python?
  13. What do you know about relational operators in Python?
  14. What are assignment operators in Python?
  15. What are membership operators?
  16. Explain identity operators in Python.
  17. What data types does Python support?

Basic to Advanced Python Coding Interview Questions 2021 for Freshers

  1. What is NumPy array?
  2. How do you debug a Python program?
  3. What is <Yield> Keyword in Python?
  4. How to convert a list into a string?
  5. What is a negative index in Python?
  6. How to convert a list into a tuple?
  7. How can you create Empty NumPy Array In Python?
  8. How to convert a list into a set?
  9. How do you Concatenate Strings in Python?
  10. How to count the occurrences of a particular element in the list?
  11. How to generate random numbers in Python?
  12. Write a Python Program to Find the Second Largest Number in a List?
  13. Write a Python Program to Check if a Number is a Prime Number?
  14. How to print sum of the numbers starting from 1 to 100?
  15. Write a Python Program to Count the Number of Digits in a Number?
  16. What is the output when we execute list(“hello”)?
  17. Write a program to find the sum of the digits of a number in Python?
  18. Write a program to reverse a number in Python?
  19. Write a Python Program to Count the Number of Vowels in a String?
  20. What is the output of the below program?
>>>names = ['Chris', 'Jack', 'John', 'Daman']
>>>print(names[-1][-1])

Interviews are very different from academics. In an interview, apart from the textbook knowledge and practical understanding, the approach to solving the problem is very crucial. To prepare for a Python interview, it is critical that your knowledge of the subject is effectively communicated to the interviewer.

This page has been written with the objective of helping readers to prepare for an exam or an interview. It contains probable questions and their solutions. We have compiled Python Interview Questions and Answers for Freshers & Experts to prepare for an exam or an interview. Over preparation can be overwhelming especially for students who are preparing for exams or interviewing for their first job. This is your guide to success !!

Python Interview Questions and Answers for Freshers & Experienced Read More »

numpy.linspace() | Create same sized samples over an interval in Python

Create a Numpy array of evenly spaced samples over a range using numpy.linspace()

In this article we will discus about how to create a Numpy array of evenly spaced samples over a range using numpy.linspace().

Numpy.linspace()

Numpy module provides a function numpy.linspace() to create a evenly spaced samples over a specified interval i.e.

Syntax: numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
Where,
  • start : Represents the start value of the range
  • stop : Represents the end value of the range (Actually array doesn’t include this value but it acts as an end point)
  • num : Represents the number of samples to be generated (If it is not provided then optional value is taken as 50)
  • dtype : Represents datatype of elements.

To use Numpy we have to include the below module i.e.

import numpy as np

Let’s see below two examples to understand the concept.

Example-1 : Create 5 evenly spaced samples in interval [10, 50]

import numpy as np
# Create 5 evenly spaced samples in interval [10, 50]
temp_arr = np.linspace(10,50,5)
print(temp_arr)
Output :
[10. 20. 30. 40. 50.]
We can also specify the datatype as int32 by dtype.
import numpy as np
# Create 5 evenly spaced samples in interval [10, 50]
temp_arr = np.linspace(10,50,5,dtype=np.int32)
print(temp_arr)
Output :
[10 20 30 40 50]

Example-2 : Get the Step size from numpy.linspace()

When we will pass retstep=True in numpy.linspace().

Then it will return step size between samples.
import numpy as np
# Create 5 evenly spaced samples in interval [10, 50]
temp_arr, step = np.linspace(10,50,5,dtype=np.int32,retstep=True)
print('Printing the Numpy Array contents: ')
print(temp_arr)
print('The step size between two samples  : ', step)
Output :
Contents of the Numpy Array : 
[10 20 30 40 50]
Step size between two elements : 10.0

numpy.linspace() | Create same sized samples over an interval in Python Read More »

Create Numpy Array of different shapes & initialize with identical values using numpy.full() in Python

Creating Numpy Array of different shapes & initialize with identical values using numpy.full()

In this article we will see how we can create a numpy array of different shapes but initialized with identical values. So, let’s start the explore the concept to understand it well.

numpy.full() :

Numpy module provides a function numpy.full() to create a numpy array of given shape and initialized with a given value.

Syntax : numpy.full(shape, given_value, dtype=None, order='C')

Where,

  • shape : Represents shape of the array.
  • given_value : Represents initialization value.
  • dtype : Represents the datatype of elements(Optional).

But to use Numpy we have to include following module i.e.

import numpy as np
Let’s see the below example to understand the concept.

Example-1 : Create a 1D Numpy Array of length 8 and all elements initialized with value 2

Here array length is 8 and array elements to be initialized with 2.

Let’s see the below the program.

import numpy as np
# 1D Numpy Array created of length 8 & all elements initialized with value 2
sample_arr = np.full(8,2)
print(sample_arr)
Output :
[2 2 2 2 2 2 2 2]

Example-2 : Create a 2D Numpy Array of 3 rows | 4 columns and all elements initialized with value 5

Here 2D array of row 3 and column 4 and array elements to be initialized with 5.

Let’s see the below the program.

import numpy as np
#Create a 2D Numpy Array of 3 rows & 4 columns. All intialized with value 5
sample_arr = np.full((3,4), 5)
print(sample_arr)
Output :
[[5 5 5 5]
[5 5 5 5]
[5 5 5 5]]

Example-3 : Create a 3D Numpy Array of shape (3,3,4) & all elements initialized with value 1

Here initialized value is 1.

Let’s see the below the program.

import numpy as np
# Create a 3D Numpy array & all elements initialized with value 1
sample_arr = np.full((3,3,4), 1)
print(sample_arr)
Output :

[[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]]

Example-4 : Create initialized Numpy array of specified data type

Here, array length is 8 and value is 4 and data type is float.

import numpy as np
# 1D Numpy array craeted & all float elements initialized with value 4
sample_arr = np.full(8, 4, dtype=float)
print(sample_arr)
Output :
[4. 4. 4. 4. 4. 4. 4. 4.]

Create Numpy Array of different shapes & initialize with identical values using numpy.full() in Python Read More »

numpy.arange() : Create a Numpy Array of evenly spaced numbers in Python

Creating a Numpy Array of evenly spaced numbers in Python

This article is all about In this article creating a Numpy array of evenly spaced numbers over a given interval using the function numpy.arrange().

numpy.arrange() :

Numpy module in python provides a function numpy.arrange() to create an Numpy Array of evenly space elements within a given interval. Actually it returns an evenly spaced array of numbers from the range-array starting from start point to stop point with equal step intervals.

Syntax- numpy.arange([start, ]stop, [step, ]dtype=None)

Where 

  • start : Represents the start value of range. (As it’s optional, so if not provided it will consider default value as 0)
  • stop : Represents the end value of range. (Actually it doesn’t include this value but it acts as an end point indicator)
  • step : Represents the spacing between two adjacent values. (As it’s optional, so if not provided it will consider default value as 1)
  • dtype : Represents data type of elements.

But to use this Numpy module we have to import following module i.e.

import numpy as np
Let’s see below examples to understand the concept well.

Example-1 : Create a Numpy Array containing numbers from 4 to 20 but at equal interval of 2

Here start is 4, stop is 20 and step is 2.
So let’s see the below program.
import numpy as np
# Start = 4, Stop = 20, Step Size = 2
#achieving the result using arrange()
sample_arr = np.arange(4, 20, 2)
#printing the output
print(sample_arr)
Output :
[ 4 6 8 10 12 14 16 18]

Example-2 : Create a Numpy Array containing numbers from 1 to 15 but at default interval of 1

Here start is 1, stop is 15 and step is default i.e 1.
So let’s see the below program.
import numpy as np
# Start = 1, Stop = 15, Step Size = 1(default)
#achieving the result using arrange()
sample_arr = np.arange(1, 15)
#printing the output
print(sample_arr)
Output :
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14]

Example-3 : Create a Numpy Array containing numbers upto 15 but start and step is default

Here start is default i.e 0, stop is 15 and step is default i.e 1.
So let’s see the below program.
import numpy as np
# Start = 0(default), Stop = 15, Step Size = 1(default)
#achieving the result using arrange()
sample_arr = np.arange(15)
#printing the output
print(sample_arr)
Output :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]

numpy.arange() : Create a Numpy Array of evenly spaced numbers in Python Read More »

Find max value & its index in Numpy Array | numpy.amax()

Finding max value and it’s index in Numpy Array

In this article we will discuss about how we can find max value and the index of that max value in Numpy array using numpy.amx().

numpy.amax( ) :

Syntax-numpy.amax(arr, axis=None, out=None, keepdims=<no value>, initial=<no value>)

Parameters :

  1. arr: Numpy array
  2. axis: This is an optional parameter unless provided flattens the array.

(Default: Returns the array of max values)

  1. Axis = 0: Returns array containing max values of each columns
  2. Axis = 1: Returns array containing max values of each rows

Let’s see one by one how to find it in 1D and 2D Numpy array.

Maximum value & its index in a 1D Numpy Array:

Let’s create a 1D numpy array from a list given below and find the maximum values and its index

Find maximum value:

To find the maximum value in the array, we can use numpy.amax( ) function and pass the array as function to it.

[10,5,19,56,87,96,74,15,50,12,98]
import numpy as np

# Finding the maximum value inside an array using amax( )
arr = np.array([10, 5, 19, 56, 87, 96, 74, 15, 50, 12, 98])
maxElem = np.amax(arr)
print("Max element : ", maxElem)
Output :
Max element :  98

Find index of maximum value :

To get the index of the max value in the array, we will we have to use the where( ) function from the numpy library.

CODE:

import numpy as np

# Index of the maximum element
arr = np.array([10, 5, 19, 56, 87, 96, 74, 15, 50, 12, 98])
maxElem = np.amax(arr)
print("Max element : ", maxElem)
res = np.where(arr == np.amax(arr))
print("Returned result  :", res)
print("List of Indices of maximum element :", res[0])
Output :
Max element :  98
Returned result  : (array([10], dtype=int32),)
List of Indices of maximum element : [10]

Here, when we called the where( ) function, it returned us with a tuple of  arrays containing the indices of all the  values that follow our conditions.

Find maximum value & its index in a 2D Numpy Array

We will use the following 2D array to demonstrate.

{50,59,54}

{45,46,78}

{98,20,24}

Find max value in complete 2D numpy array :

When we are going to find the max value in a 2D numpy array, we can either do it by finding a single value or we can find column wise or row wise.

CODE:

import numpy as np

arr = np.array([[50, 59, 54], [45, 46, 78], [98, 20, 24]])
# Get the maximum value from the 2D array

maxValue = np.amax(arr)
print("The maximum value inside the array is", maxValue)
Output :
The maximum value inside the array is 98

Column or Row wise value

To find the max value per each row, we can  pass axis =1 and for columns we can use axis =0.

CODE:

import numpy as np

arr = np.array([[50, 59, 54], [45, 46, 78], [98, 20, 24]])
# Get the maximum valuevin rows
maxRows = np.amax(arr, axis=1)
# Get the maximum valuevin columns
maxColumns = np.amax(arr, axis=0)

print(
    "The maximum values in rows are : ",
    maxRows,
    " and the maximum value in columns are : ",
    maxColumns,
)
Output :
The maximum values in rows are :  [59 78 98]  and the maximum value in columns are :  [98 59 78]

Find index of maximum value from 2D numpy array:

CODE:

import numpy as np

arr = np.array([[50, 59, 54], [45, 46, 78], [98, 20, 24]])
# Get the index of max value inside the 2D array
res = np.where(arr == np.amax(arr))
print("Tuple :", res)
print("Now Coordinates of max value in 2D array :")
# zipping both the arrays to find the coordinates
Coordinates = list(zip(res[0], res[1]))

for elem in Coordinates:
    print(elem)

Output :
Tuple : (array([2], dtype=int32), array([0], dtype=int32))
Now Coordinates Of max value in 2D array :
(2, 0)

numpy.amax() & NaN :

amax( ) also propagates the NaN values , which means if there is a NaN value present in the numpy array, then the max value returned by the function will be NaN.

import numpy as np

arr = np.array([[50, 59, np.NaN], [45, 46, 78], [98, 20, 24]])
# amax( ) propagating the NaN values

print("The max element in the numpy array is :", np.amax(arr))
Output :
The max element in the numpy array is : nan

 

 

 

Find max value & its index in Numpy Array | numpy.amax() Read More »

Pandas : How to Merge Dataframes using Dataframe.merge() in Python – Part 1

Merging Dataframes using Dataframe.merge() in Python

In this article, we will learn to merge two different DataFrames into a single one using function Dataframe.merge().

Dataframe.merge() :

Dataframe class of Python’s Pandas library provide a function i.e. merge() which helps in merging of two DataFrames.

Syntax:- DataFrame.merge(right, how='inner', on=None, leftOn=None, rightOn=None, left_index=False, right_index=False, sort=False, suffix=('_x', '_y'), copy=True, indicate=False, validate=None)

Arguments:-

  • right : A dataframe that is to be merged with the calling dataframe.
  • how : (Merge type). Some values are : left, right, outer, inner. It’s default value is ‘inner’. If the two dataframes contains different columns, then based how value, columns will be considered accordingly for merging.
  • on : It is the column name on which merge will be done. If not provided then merged done on basis of indexes.
  • left_on : Column in left dataframe where merging is to be done.
  • right_on : Column in right datframe, where merging is to be done.
  • left_index : (bool), default is False (If found True index index from left dataframe selected as join key)
  • right_index : (bool), default is False (If found True index index from right dataframe selecte as join key)
  • suffixes : tuple of (str, str), default (‘_x’, ‘_y’)
  • Suffix that is to be applied on overlapping columns in left and right dataframes respectively.

Let’s see one by one

Merge DataFrames on common columns (Default Inner Join) :

If we have two DataFrames of two common columns, by directly calling merge()  function the two columns will be merged considering common columns as join keys and the dissimilar columns would just be copied from one dataframe to another dataframe.

Let’s see the below program to understand it clearly.

import pandas as sc
# List of Tuples
players = [(15,'Smith','Pune', 17,12000),
            (99,'Rana', 'Mumbai', 20,2000),
            (51,'Jaydev','Kolkata', 22,25640),
            (31,'Shikhar','Hyderabad', 28,85410),
            (12,'Sanju','Rajasthan', 21,63180),
            (35,'Raina','Gujarat', 18,62790)
            ]
# Creation of DataFrame object
playDFObj = sc.DataFrame(players, columns=['JersyN','Name', 'Team', 'Age','Sponsered'], index=['I', 'II', 'III', 'IV', 'V', 'VI'])
print('DataFrame 1 : ')
print(playDFObj)
moreInfo = [(15, 13, 180000, 12000) ,
           (99, 2, 195200, 2000) ,
           (51, 7, 15499, 25640) ,
           (31, 17, 654000, 85410) ,
           (12, 5, 201000, 63180) ,
           (35, 14, 741000, 62790)
            ]
# Creation of DataFrame object
moreinfoObj = sc.DataFrame(moreInfo, columns=['JersyN', 'PLayingSince' , 'Salary', 'Sponsered'], index=['I', 'II', 'III', 'IV', 'V', 'VI'])
print('DataFrame 2 : ')
print(moreinfoObj)
# Merge two Dataframes on basis of common column by default INNER JOIN
mergedDataf = playDFObj.merge(moreinfoObj)
print(mergedDataf)
Output :
DataFrame 1 :
     JersyN     Name       Team  Age  Sponsered
I        15    Smith       Pune   17      12000
II       99     Rana     Mumbai   20       2000
III      51   Jaydev    Kolkata   22      25640
IV       31  Shikhar  Hyderabad   28      85410
V        12    Sanju  Rajasthan   21      63180
VI       35    Raina    Gujarat   18      62790
DataFrame 2 :
     JersyN  PLayingSince  Salary  Sponsered
I        15            13  180000      12000
II       99             2  195200       2000
III      51             7   15499      25640
IV       31            17  654000      85410
V        12             5  201000      63180
VI       35            14  741000      62790
   JersyN     Name       Team  Age  Sponsered  PLayingSince  Salary
0      15    Smith       Pune   17      12000            13  180000
1      99     Rana     Mumbai   20       2000             2  195200
2      51   Jaydev    Kolkata   22      25640             7   15499
3      31  Shikhar  Hyderabad   28      85410            17  654000
4      12    Sanju  Rajasthan   21      63180             5  201000
5      35    Raina    Gujarat   18      62790            14  741000

What is Inner Join ?

In above case, inner join occured for key columns i.e. ‘JersyN’ & ‘Sponsered’. During inner join the common columns of two dataframes are picked and merged. We can also explicitly do inner join by passing how argument with values as inner. After implementing both the cases will have same result.

Merge Dataframes using Left Join :

What is left join ?

While merging columns we can include all rows from left DataFrame and NaN from which values are missing in right DataFrame.

Let’s see the below program to understand it clearly.

import pandas as sc
# List of Tuples
players = [(15,'Smith','Pune', 17,12000),
            (99,'Rana', 'Mumbai', 20,2000),
            (51,'Jaydev','Kolkata', 22,25640),
            (31,'Shikhar','Hyderabad', 28,85410),
            (12,'Sanju','Rajasthan', 21,63180),
            (35,'Raina','Gujarat', 18,62790)
            ]
# Creation of DataFrame object
playDFObj = sc.DataFrame(players, columns=['JersyN','Name', 'Team', 'Age','Sponsered'], index=['I', 'II', 'III', 'IV', 'V', 'VI'])
print('DataFrame 1 : ')
print(playDFObj)
moreInfo = [(15, 13, 180000, 12000) ,
           (99, 2, 2000) ,
           (51, 7, 15499, 25640) ,
           (31, 17, 654000) ,
           (12, 5, 201000, 63180) ,
           (35, 14, 741000, 62790)
            ]
# Creation of DataFrame object
moreinfoObj = sc.DataFrame(moreInfo, columns=['JersyN', 'PLayingSince' , 'Salary', 'Sponsered'], index=['I', 'II', 'III', 'IV', 'V', 'VI'])
print('DataFrame 2 : ')
print(moreinfoObj)
# Merge two Dataframes on basis of common column by default INNER JOIN
mergedDataf = playDFObj.merge(moreinfoObj, how='left')
print('After merging: ')
print(mergedDataf)
Output :
DataFrame 1 :
     JersyN     Name       Team  Age  Sponsered
I        15    Smith       Pune   17      12000
II       99     Rana     Mumbai   20       2000
III      51   Jaydev    Kolkata   22      25640
IV       31  Shikhar  Hyderabad   28      85410
V        12    Sanju  Rajasthan   21      63180
VI       35    Raina    Gujarat   18      62790
DataFrame 2 :
     JersyN  PLayingSince  Salary  Sponsered
I        15            13  180000    12000.0
II       99             2    2000        NaN
III      51             7   15499    25640.0
IV       31            17  654000        NaN
V        12             5  201000    63180.0
VI       35            14  741000    62790.0
After merging:
   JersyN     Name       Team  Age Sponsered  PLayingSince    Salary
0      15    Smith       Pune   17     12000          13.0  180000.0
1      99     Rana     Mumbai   20      2000           NaN       NaN
2      51   Jaydev    Kolkata   22     25640           7.0   15499.0
3      31  Shikhar  Hyderabad   28     85410           NaN       NaN
4      12    Sanju  Rajasthan   21     63180           5.0  201000.0
5      35    Raina    Gujarat   18     62790          14.0  741000.0

Merge DataFrames using Right Join :

What is Right join ?

While merging columns we can include all rows from right DataFrame and NaN from which values are missing in left DataFrame.

Let’s see the below program to understand it clearly.

import pandas as sc
# List of Tuples
players = [(15,'Smith','Pune', 17,12000),
            (99,'Rana', 'Mumbai', 20,2000),
            (51,'Jaydev','Kolkata', 22,25640),
            (31,'Shikhar','Hyderabad', 28,85410),
            (12,'Sanju','Rajasthan', 21,63180),
            (35,'Raina','Gujarat', 18,62790)
            ]
# Creation of DataFrame object
playDFObj = sc.DataFrame(players, columns=['JersyN','Name', 'Team', 'Age','Sponsered'], index=['I', 'II', 'III', 'IV', 'V', 'VI'])
print('DataFrame 1 : ')
print(playDFObj)
moreInfo = [(15, 13, 180000, 12000) ,
           (99, 2, 2000) ,
           (51, 7, 15499, 25640) ,
           (31, 17, 654000) ,
           (12, 5, 201000, 63180) ,
           (35, 14, 741000, 62790)
            ]
# Creation of DataFrame object
moreinfoObj = sc.DataFrame(moreInfo, columns=['JersyN', 'PLayingSince' , 'Salary', 'Sponsered'], index=['I', 'II', 'III', 'IV', 'V', 'VI'])
print('DataFrame 2 : ')
print(moreinfoObj)
# Merge two Dataframes on basis of common column by default INNER JOIN
mergedDataf = playDFObj.merge(moreinfoObj, how='right')
print('After merging: ')
print(mergedDataf)
Output :
DataFrame 1 :
     JersyN     Name       Team  Age  Sponsered
I        15    Smith       Pune   17      12000
II       99     Rana     Mumbai   20       2000
III      51   Jaydev    Kolkata   22      25640
IV       31  Shikhar  Hyderabad   28      85410
V        12    Sanju  Rajasthan   21      63180
VI       35    Raina    Gujarat   18      62790
DataFrame 2 :
     JersyN  PLayingSince  Salary  Sponsered
I        15            13  180000    12000.0
II       99             2    2000        NaN
III      51             7   15499    25640.0
IV       31            17  654000        NaN
V        12             5  201000    63180.0
VI       35            14  741000    62790.0
After merging:
   JersyN    Name       Team   Age  Sponsered  PLayingSince  Salary
0      15   Smith       Pune  17.0    12000.0            13  180000
1      51  Jaydev    Kolkata  22.0    25640.0             7   15499
2      12   Sanju  Rajasthan  21.0    63180.0             5  201000
3      35   Raina    Gujarat  18.0    62790.0            14  741000
4      99     NaN        NaN   NaN        NaN             2    2000
5      31     NaN        NaN   NaN        NaN            17  654000

Merge DataFrames using Outer Join :

What is Outer join ?

While merging columns of two dataframes, we can even include all rows of two DataFrames and add NaN for the values missing in left or right DataFrame.

Let’s see the below program to understand it clearly.

import pandas as sc
# List of Tuples
players = [(15,'Smith','Pune', 17,12000),
            (99,'Rana', 'Mumbai', 20,2000),
            (51,'Jaydev','Kolkata', 22,25640),
            (31,'Shikhar','Hyderabad', 28,85410),
            (12,'Sanju','Rajasthan', 21,63180),
            (35,'Raina','Gujarat', 18,62790)
            ]
# Creation of DataFrame object
playDFObj = sc.DataFrame(players, columns=['JersyN','Name', 'Team', 'Age','Sponsered'], index=['I', 'II', 'III', 'IV', 'V', 'VI'])
print('DataFrame 1 : ')
print(playDFObj)
moreInfo = [(15, 13, 180000, 12000) ,
           (99, 2, 2000) ,
           (51, 7, 15499, 25640) ,
           (31, 17, 654000) ,
           (12, 5, 201000, 63180) ,
           (35, 14, 741000, 62790)
            ]
# Creation of DataFrame object
moreinfoObj = sc.DataFrame(moreInfo, columns=['JersyN', 'PLayingSince' , 'Salary', 'Sponsered'], index=['I', 'II', 'III', 'IV', 'V', 'VI'])
print('DataFrame 2 : ')
print(moreinfoObj)
# Merge two Dataframes on basis of common column by default INNER JOIN
mergedDataf = playDFObj.merge(moreinfoObj, how='outer')
print('After merging: ')
print(mergedDataf)
Output :
DataFrame 1 :
     JersyN     Name       Team  Age  Sponsered
I        15    Smith       Pune   17      12000
II       99     Rana     Mumbai   20       2000
III      51   Jaydev    Kolkata   22      25640
IV       31  Shikhar  Hyderabad   28      85410
V        12    Sanju  Rajasthan   21      63180
VI       35    Raina    Gujarat   18      62790
DataFrame 2 :
     JersyN  PLayingSince  Salary  Sponsered
I        15            13  180000    12000.0
II       99             2    2000        NaN
III      51             7   15499    25640.0
IV       31            17  654000        NaN
V        12             5  201000    63180.0
VI       35            14  741000    62790.0
After merging:
   JersyN     Name       Team   Age  Sponsered  PLayingSince    Salary
0      15    Smith       Pune  17.0    12000.0          13.0  180000.0
1      99     Rana     Mumbai  20.0     2000.0           NaN       NaN
2      51   Jaydev    Kolkata  22.0    25640.0           7.0   15499.0
3      31  Shikhar  Hyderabad  28.0    85410.0           NaN       NaN
4      12    Sanju  Rajasthan  21.0    63180.0           5.0  201000.0
5      35    Raina    Gujarat  18.0    62790.0          14.0  741000.0
6      99      NaN        NaN   NaN        NaN           2.0    2000.0
7      31      NaN        NaN   NaN        NaN          17.0  654000.0

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas

Pandas : How to Merge Dataframes using Dataframe.merge() in Python – Part 1 Read More »