Python ReLu Function with Examples

ReLu Function with Examples

ReLu Function:

Python has been important in improving learning models built over convolutional pictures as well as machine learning models. These deep learning models have benefited greatly because the process of building them has gotten much easier when it comes to Python’s built-in modules and functions.

In the field of deep learning, the most commonly used activation function is Relu or Rectified Linear Activation Function.

Python introduces the ReLu function, to increase the computational efficiency of deep learning models.

The ReLu function detects and displays the state of the model results, and it improves the computational efficiency of the model.

According to the ReLu activation function, if the input is negative, return 0. Otherwise, return 1.

 

ReLu Function
ReLu Function

 

ReLu Function with Examples in Python

Approach:

  • Create a function say ReLu which takes the given number as an argument and returns the maximum value of 0 and the number.
  • Return the maximum value of 0 and the number passed as an argument.
  • Give the first number as static input and store it in a variable.
  • Pass the given number as an argument to the above created ReLu() function and print the result.
  • Give the second number as static input and store it in another variable.
  • Pass the given number as an argument to the above created ReLu() function and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a function say ReLu which takes the given number as an argument 
# and returns the maximum value of 0 and the number
def ReLu(gvn_num1):
    # Return the maximum value of 0 and the number passed as an argument 
    return max(0.0, gvn_num1)

# Give the first number as static input and store it in a variable
gvn_num1 = 2.0
# Pass the given number as an argument to the above created ReLu() function and print the result
print(ReLu(gvn_num1))
# Give the second number as static input and store it in another variable
gvn_num2 = -3.0
# Pass the given number as an argument to the above created ReLu() function and print the result
print(ReLu(gvn_num2))

Output:

2.0
0.0

Gradient value of the ReLu function

When dealing with data for mining and processing, when attempting to calculate the derivative of the ReLu function, for values less than zero, i.e. negative values, the gradient is 0. This implies that the weights and biases for the learning function are not being updated in accordingly. This could cause issues with the model’s training.

We will talk about the Leaky ReLu function to solve this constraint of the ReLu function.

Leaky ReLu function

The Leaky ReLu function is an extension of the standard ReLu function. To overcome the issue of zero gradient for negative value, Leaky ReLu provides a very small linear component of x to negative inputs.

Leaky ReLu can be expressed mathematically as:

f(x) = 0.01x,  x<0

      = x,    x>=0

Example

Approach:

  • Create a function say Relu_fun() which takes the given number as an argument and returns a number.
  • Check if the given number is greater than 0 using the if conditional statement.
  • If it is true, then return the given number.
  • Else return the given number multiplied with 0.001.
  • Give the number as static input and store it in a variable.
  • Pass the given number as an argument to the above created Relu_fun() function and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a function say Relu_fun which takes the given number as an argument.
def Relu_fun(gvn_num):
  # Check if the given number is greater than 0 using the if conditional statement
  if gvn_num>0 :
    # If it is true, then return the given number
    return gvn_num
  else :
    # Else return the given number multiplied with 0.001
    return 0.001*gvn_num
 
# Give the number as static input and store it in a variable
gvn_num = -3
# Pass the given number as an argument to the above created Relu_fun() function 
# and print the result
print(Relu_fun(gvn_num))

Output:

-0.003

 

How to Handle IOErrors in Python?

How to Handle IOErrors in Python

In this post, we’ll look at how to handle IOErrors in Python. Assume we are doing a mathematical operation on a specific example. This can be even more terrible if it is prolonged. The primary issue arises when we are stranded somewhere. We solved it with a lot of effort. However, the answer is either insufficient or incorrect. There are two options for this:

Either the problem we’re attempting to tackle was built wrongly from the start.
Or we are providing incorrect input throughout the entire procedure or steps.
In a single phrase, the entire thing is an error.

They can come in a variety of forms, depending on the circumstances. It is determined by the nature of the problem. Errors occur in programming in the same way. They are the various types of output that occur in particular situations.

IOErrors in Python:

If we encounter a file-related error while dealing with Input and Output Operations in Python, the function will throw the IOError. When we attempt to open a file and it does not exist, the IOError occurs. Even though the statement or line of code is correct, it may result in an error during execution. This kind of errors, which are noticed during program execution, are now referred to as exceptions. The IOError is commonly produced when an input-output operation, such as open() file, or a function, or a simple print statement, fails owing to IO reasons such as “Disk full” or “File not found.” The IOError class derives from the EnvironmentError.

Syntax:

IOError: [Errno 1] No such file or directory: 'file.txt'

Begin with the error name, IOError, and then the error number that happened in a single application using the Errno keyword. The message that explains why the problem occurred, which is common. There is no such file or directory, which means that the file name we entered is either not available at the specified place or the location is incorrect. The name of the file that we have passed is at the end. This assists us in determining which file to search for or rename. The syntax is meant to assist programmers in resolving errors and moving forward.

Working With IOError

  • We give the file name and path of the file location in a Python program where we have a simple action of printing the content of a file.
  • However, if the file we passed does not exist at the passed location or if the file name has been changed, the operation we wish to perform will fail.
  • This will result in an IOError fault relating to Input-Output.
  • So, IOError is an exception type error that occurs when the file we passed in as an argument does not exist, has a different name, or the file location path is incorrect.
  • Any of these causes could result in an IOError.
  • There are numerous more problems that can occur, and we have handled these errors based on the code’s requirements.

Handle IOErrors in Python

In general, this exception has a new name in newer Python versions.

Example1: Open a File 

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in read-only mode. In this case, we're simply just reading the contents of the file.
gvn_file = open(givenFilename, 'r') 
# Print the name of the file using the name attribute
print('Given File = ', gvn_file.name)
# Print the mode of the file using the mode attribute
print('Given File mode = ', gvn_file.mode)

Output:

Opening a File

Example1: Close a File 

# Close the given file using the close() function
gvn_file.close()
# Check whether the file is closed or not using closed
print('Check whether the file is closed or not: ', gvn_file.closed)

Output:

Closing a file

Now we will remove/delete the file and then attempt to open it, which will result in the appropriate error.

# Open the file in read-only mode. In this case, we're simply just reading the contents of the file.
gvn_file = open(givenFilename, 'r')

Output:

Opening a file after deleting it

 

IOError is a subclass of FileNotFoundError. We can also identify it using Python’s Exception Handling techniques.

Let us now utilize the try and except block to handle our filenotfounderror and produce a more readable response.

Handling IOError:

# Open the file in try block
try:
    # Make a single variable to store the path of the file. This is a constant value.
    # This value must be replaced with the file path from your own system in the example below.
    givenFilename = "samplefile.txt"
    # Open the file in read-only mode. In this case, we're simply just reading the contents of the file.
    gvn_file = open(givenFilename, 'r') 
    # Print some random text for acknowledgment
    print('your file is opened')
     
# Handle the IOError using the except block
except IOError:
    # Print some random text for easy understanding of error
    print('sorry there is no such file')

Output:

sorry there is no such file

Handling IOError

Explanation:

Here we tried to handle the IOError using the try-except blocks with some user understandable message.

Python imread()- Different ways to Load an Image Using the OpenCV.imread() Method

imread()- Different ways to Load an Image Using the OpenCV.imread() Method

imread() Method:

imread() is one of the OpenCV-Python library’s most useful and often used methods. It is used to load an image from the given file into the Python program. After successfully importing the picture, it returns a numpy.ndarray (NumPy N-dimensional array). When a colorful image is loaded, this numpy.ndarray is a 3-Dimensional array; when a grayscale image is loaded, this numpy.ndarray is a 2-Dimensional array.

OpenCV-Python is a Python binding library for solving computer vision problems.

The cv2 module of the opencv-python library is required to use the Python imread() method.

Before we start with the code, first we should install the opencv-python library into our environment as shown below:

pip install  opencv-python
# Import cv2 module using the import keyword
import cv2

Syntax:

cv2.imread(filename/path, flag)

Parameters

filepath: It is a string that represents the image’s path to be read.

flag: This is optional parameter. It normally accepts one of three values: cv2.IMREAD COLOR, cv2.IMREAD GRAYSCALE, and cv2.IMREAD UNCHANGED. This option, in fact, specifies the mode in which the picture should be read.

Note: The value of this flag parameter is cv2.IMREAD COLOR or 1 by default.

Return Value:

  • If the picture is successfully loaded, the cv2.imread() method returns a numpy.ndarray
  • If the image cannot be read for whatever reason, it returns an empty matrix (Mat::data==NULL) (like missing file, improper permissions, unsupported or invalid format).

Python’s imread() function supports the below image formats:

  • Portable Network Graphics : *.png
  • Portable image format: *.pbm, *.pgm, *.ppm *.pxm, *.pnm
  • JPEG files: *.jpeg, *.jpg, *.jpe
  • Windows bitmaps: *.bmp
  • JPEG 2000 files: *.jp2
  • WebP: *.webp
  • Sun rasters: *.sr, *.ras
  • PFM files: *.pfm
  • OpenEXR Image files: *.exr
  • TIFF files: *.tiff, *.tif
  • Radiance HDR: *.hdr, *.pic

Reading images in.JPEG format is dependent on the version of the OpenCV library present on the system, platform, or environment (such as x86/ARM), and so on. The most important thing to remember is that the kind of picture is decided by the content of the numpy.ndarray returned by the cv2.imread() method, not by the image file extension.

Let us take the below sample image:

Sample Image for Implementation purpose

1)Load an image using cv2.IMREAD_COLOR

cv2.IMREAD_COLOR: This specifies that a color image should be loaded. Any image transparency will be ignored. It is the default setting. We can also pass the integer value 1 for this flag.

When the flag cv2.IMREAD COLOR is set, the picture is converted to a three-channel BGR color image with no transparency channel before being imported into the program.

Example

Approach:

  • Import cv2 module using the import keyword.
  • Pass the image file path, in cv2.IMREAD_COLOR mode as arguments to the imread() function to load the given image.
  • Store it in a variable.
  • Print the shape(dimensions) of the given image using the shape attribute
  • The Exit of the Program.

Below is the implementation:

# Import cv2 module using the import keyword
import cv2
# Pass the image file path,in cv2.IMREAD_COLOR mode as arguments to the imread() function
# to load the given image.
# Store it in a variable.
gvn_imag = cv2.imread('dhoni.jpg', cv2.IMREAD_COLOR) 
# Print the shape of given image using the shape attribute
print("The shape of the given image = ", gvn_imag.shape)

Output:

The shape of the given image = (194, 259, 3)

Explanation:

There are three values in the output tuple. In the given sample image, 194 is the number of rows (height of the image), 259 is the number of columns (width of the image), and 3 is the number of channels.

Because the flag value is cv2.IMREAD COLOR, the loaded image only includes three channels: blue, green, and red.

2)Load an image using cv2.IMREAD_GRAYSCALE

cv2.IMREAD_GRAYSCALE: It instructs the system to load an image in grayscale mode. We can also pass the integer value 0 for this flag.

Example

Approach:

  • Import cv2 module using the import keyword.
  • Pass the image file path, in cv2.IMREAD_GRAYSCALE mode as arguments to the imread() function to load the given image.
  • Store it in a variable.
  • Print the shape(dimensions) of the given image using the shape attribute
  • The Exit of the Program.

Below is the implementation:

# Import cv2 module using the import keyword
import cv2
# Pass the image file path,in cv2.IMREAD_GRAYSCALE mode as arguments to the imread() function
# to load the given image.
# Store it in a variable.
gvn_imag = cv2.imread('dhoni.jpg', cv2.IMREAD_GRAYSCALE) 
# Print the shape of given image using the shape attribute
print("The shape of the given image = ", gvn_imag.shape)

Output:

The shape of the given image = (194, 259)

Explanation:

There are just two values in the output tuple. The number of rows in the sample image is 194, and the number of columns is 259. When the flag value is either 0 or cv2.IMREAD GRAYSCALE, the image will be loaded as a grayscale image regardless of the input sample image given to the cv2.imread() method.

3)Load an image using cv2.IMREAD_UNCHANGED

cv2.IMREAD_UNCHANGED: It specifies that an image with an alpha channel is loaded. Alternatively, we can set this flag to the integer value -1.

Example

Approach:

  • Import cv2 module using the import keyword.
  • Pass the image file path, in cv2.IMREAD_UNCHANGED mode as arguments to the imread() function to load the given image.
  • Store it in a variable.
  • Print the shape(dimensions) of the given image using the shape attribute
  • The Exit of the Program.

Below is the implementation:

# Import cv2 module using the import keyword
import cv2
# Pass the image file path,in cv2.IMREAD_UNCHANGED mode as arguments to the imread() function
# to load the given image.
# Store it in a variable.
gvn_imag = cv2.imread('dhoni.jpg', cv2.IMREAD_UNCHANGED) 
# Print the shape of given image using the shape attribute
print("The shape of the given image = ", gvn_imag.shape)

Output:

The shape of the given image = (194, 259, 3)

Explanation:

There are three values in the output tuple. In the given sample image, 194 is the number of rows (height of the image), 259 is the number of columns (width of the image), and 3 is the number of channels i.e, blue, green, and red.

Note: For some Images, as the flag value is cv2.IMREAD UNCHANGED, the loaded picture has four channels: blue, green, red, and transparency.

Python Arithmetic Operations on Images

Arithmetic Operations on Images

What exactly do we mean when we say Arithmetic Operations on Images?

Image arithmetic refers to arithmetic operations performed on images. Any arithmetic operation performed on an image is performed on individual pixel values.

The input images can be subjected to arithmetic operations such as addition, subtraction, and bitwise operations. These operations can help to improve the properties of the input photos. Image arithmetic is necessary for analyzing the attributes of the input image. The operated images can then be utilized as an upgraded input image, and many more operations can be applied to the image for clarification, thresholding, dilating, and so on.

Example

If the image is colored, the addition is done as follows:

rslt_image(i, j, k) = image1(i, j, k) + image2(i, j, k) 
(or)
rslt_image(i, j, k) = image1(i, j, k) + constant

If the image is grayscale, the addition is performed as follows:

rslt_image(i, j) = image1(i, j) + image2(i, j) 
(or)
rslt_image(i, j) = image1(i, j) + constant

Before going to the implementation we should first install and import the libraries:

Installation & Importing:

pip install  opencv-python
# Import cv2 module using the import keyword
import cv2

Because the images are loaded as a NumPy N-dimensional array, it is relatively simple to do various arithmetic operations on them.

Note: If arithmetic operations are performed on two or more images, all images must be of the same kind, such as jpeg, jpg, png, etc., **depth, and dimensions.

**depth: The number of bits used to represent each pixel, such as 8 bits per channel in a 24-bit color image (8 bits x 3 channels).

Arithmetic Operations on Images in Python

Let us take the below two samples images as an example:

Sample Image1:

Sample Image1

Sample Image2:

Sample Image2

1)Image Addition

We can add two images using the OpenCV method cv2.add() or a simple numpy operation

rslt_img = image1 + image2

Both images must have the same depth and type, alternatively, the second image can simply be a scalar number.

NumPy Addition: We just import the image files and use the (+) operator to add the NumPy N-d arrays returned after loading the images. It is a modulo operation, which means that if the resultant pixel value is greater than 255 after adding the pixel values of the input images, the modulo (%) of the resultant pixel value with 256 (for 8-bit image format) is calculated and assigned to the resultant pixel value to keep it below 255 or 255, as no pixel value can exceed 255.

Example:

250 + 10 = 260 –> 260 % 256 = 4

Example

Approach:

  • Import cv2 module using the import keyword.
  • Pass the image1 file path as an argument to the imread() function to load/open the given image and store it in a variable.
  • Pass the image2 file path as an argument to the imread() function to load/open the given image and store it in another variable.
  • Add both the given images using the ‘+’ operator and store it in another variable.
  • Save the above result in another file using the imwrite() function by passing the filename as an argument to it.
  • The Exit of the Program.

Below is the implementation:

# Import cv2 module using the import keyword
import cv2
# Pass the image1 file path as an argument to the imread() function to 
# load/open the given image and store it in a variable
gvnimag_1 = cv2.imread('dhoni.jpg')
# Pass the image2 file path as an argument to the imread() function to 
# load/open the given image and store it in another variable
gvnimag_2 = cv2.imread('dore.jpg')
 
# Add both the given images using the '+' operator and store it in another variable
rslt_imag = gvnimag_1 + gvnimag_1
 
# Save the above result in another file using the imwrite() function 
# by passing the filename as an argument to it.
cv2.imwrite('rslt_image.jpg', rslt_imag)

Output:

Addition of Two Images

OpenCV addition:

We just read the picture files and send the NumPy N-d arrays obtained after loading the images as arguments to the cv2.add() method. It is a saturated operation, which implies that if the final pixel value is more than 255 after adding the pixel values of the input (loaded) images, it is saturated to 255, and no pixel value can exceed 255. This is referred to as **saturation.

Example: 255 = 250 + 10 = 260

**Saturation is an image processing technique used to handle pixel overflow in which we set all overflowing pixels to the maximum possible values.

Example

# Import cv2 module using the import keyword
import cv2
# Pass the image file path as an argument to the imread() function to 
# load/open the given image and store it in a variable
gvnimag_1 = cv2.imread('dhoni.jpg')
# Pass the image file path as an argument to the imread() function to 
# load/open the given image and store it in another variable
gvnimag_2 = cv2.imread('second.jpg')
 
# Add both the given images using the cv2.add() operator and store it in another variable
rslt_imag = cv2.add(gvnimag_1, gvnimag_2)

# Save the above result in another file using the imwrite() function 
# by passing the filename as an argument to it.
cv2.imwrite('rslt_image.jpg', rslt_imag)

Output:

Addition of Two images using cv.add()

Note:

 Here we took images of the same pixels

2)Image Subtraction

Image subtraction is simple pixel subtraction, which takes two photos as input and outputs the third image with pixel values equal to the first image minus the equivalent pixel values from the second image. We can also take a single image and subtract a constant value from all of its pixel values. Instead of the obviously signed output, certain implementations of the operator will report the absolute difference between pixel values.

Image subtraction implementations differ in what they do if the output pixel values are negative. If the picture formats permit negative pixel values, then the negative values are acceptable. If the image format does not support negative pixel values, such pixels are frequently set to zero (i.e. black typically). Or

If the image subtraction calculates the absolute differences between two input images that utilise the same pixel value type, the output pixel values cannot be outside the specified range that may be represented by the input image’s pixel type, and so this problem is avoided. That is why absolute differences are useful. Again, we have two options for performing image subtraction:

NumPy Subtraction & OpenCV Subtraction:

Only the OpenCV subtraction will be utilized because it gives better results and is commonly used. For image subtraction, use the cv2.subtract() method, and the result will be

result_image = image1 - image2,

where image1 and image12are images of the same depth and type.

Image subtraction is employed as both an intermediate step in more complex image processing techniques and as a standalone operation. One of the most popular applications of picture subtraction is to remove background lighting changes from a scene so that the items in the foreground can be evaluated more easily and clearly.

Example1

Below is the implementation:

# Import cv2 module using the import keyword
import cv2
# Pass the image file path as an argument to the imread() function to 
# load/open the given image and store it in a variable
gvnimag_1 = cv2.imread('dhoni.jpg')
# Pass the image file path as an argument to the imread() function to 
# load/open the given image and store it in another variable
gvnimag_2 = cv2.imread('second.jpg')
 
# Subtract both the given images using the '-' operator and store it in another variable
rslt_imag = gvnimag_1 - gvnimag_1
 
# Save the above result in another file using the imwrite() function 
# by passing the filename as an argument to it.
cv2.imwrite('rslt_image.jpg', rslt_imag)

Output:

Subtraction of Two Images

Example2

Below is the implementation:

# Import cv2 module using the import keyword
import cv2
# Pass the image file path as an argument to the imread() function to 
# load/open the given image and store it in a variable
gvnimag_1 = cv2.imread('dhoni.jpg')
# Pass the image file path as an argument to the imread() function to 
# load/open the given image and store it in another variable
gvnimag_2 = cv2.imread('second.jpg')
 
# Subtract both the given images using the cv2.subtract() method and store it in another variable
rslt_imag = cv2.subtract(gvnimag_1, gvnimag_2)

# Save the above result in another file using the imwrite() function 
# by passing the filename as an argument to it.
cv2.imwrite('rslt_image.jpg', rslt_imag)

Output:

Subtraction of Two images using cv.subtract()

3)Image Multiplication

Image multiplication, like other mathematical operations on images, can be implemented in forms. The first type of image multiplication takes two input images and produces an output image with pixel values that are the product of the input images’ corresponding pixel values.

The second variant takes a single input image and generates output in which each pixel value is the product of the input image’s corresponding pixel values plus a constant (scaling factor). This second type of image multiplication is more commonly utilized and is known as scaling.

There are various applications for image scaling, but in general, a scaling factor greater than unity brightens the image, while a scale factor smaller than unity darkens the image.

Because it preserves the relative contrast of the image, scaling produces a much more natural brightening or darkening impact in the image than just adding an offset to the pixel values.

The constant value is frequently a floating-point number that can be used to raise or reduce the image intensity. It can be negative if the image format supports it. If the estimated output values are greater than the maximum allowable pixel value, the output is truncated at that value.

Example1

Below is the implementation:

# Import cv2 module using the import keyword
import cv2
# Pass the image file path as an argument to the imread() function to 
# load/open the given image and store it in a variable
gvnimag_1 = cv2.imread('dhoni.jpg')
 
# Multiply the given image with some random number using the '*' operator 
# and store it in another variable
rslt_imag = gvnimag_1 *2.3
 
# Save the above result in another file using the imwrite() function 
# by passing the filename as an argument to it.
cv2.imwrite('mult_image.jpg', rslt_imag)

Output:

Multiplication of Image with Constant Value

Example2

Below is the implementation:

# Import cv2 module using the import keyword
import cv2
# Pass the image file path as an argument to the imread() function to 
# load/open the given image and store it in a variable
gvnimag_1 = cv2.imread('dhoni.jpg')
 
# Multiply the given image with some random number using the cv2.multiply() function
# and store it in another variable
rslt_imag = cv2.multiply(gvnimag_1, 0.9)

# Save the above result in another file using the imwrite() function 
# by passing the filename as an argument to it.
cv2.imwrite('mult_image.jpg', rslt_imag)

Output:

Multiplication of image with a constant value using cv.multiply

4)Image Division

The image division procedure generally takes two images as input and outputs a third image whose pixel values are the first image’s pixel values divided by the second image’s corresponding pixel values.

It can also be used with a single input image, in which case each pixel value is split by a constant.

Image division can be used for change detection in the same way that subtraction can, but instead of providing the absolute change for each pixel value from one image to the next, the division provides the fractional change or ratio between matching pixel values.

Hence it is referred to as rationing.

Example1

The image division is used to reduce the brightness of the above sample image, using the cv2.divide() method, which typically accepts two image arrays or one image array and one specified constant.

Below is the implementation:

# Import cv2 module using the import keyword
import cv2
# Pass the image file path as an argument to the imread() function to 
# load/open the given image and store it in a variable
gvnimag_1 = cv2.imread('dhoni.jpg')
 
# Divide the given image with some random number using the cv2.divide() function
# and store it in another variable
rslt_imag = cv2.divide(gvnimag_1, 3)

# Save the above result in another file using the imwrite() function 
# by passing the filename as an argument to it.
cv2.imwrite('div_image.jpg', rslt_imag)

Output:

Division of Image with a Constant Value

Example2

Alternatively, we may use the NumPy division to reduce the brightness of the image.

Below is the implementation:

# Import cv2 module using the import keyword
import cv2
# Pass the image file path as an argument to the imread() function to 
# load/open the given image and store it in a variable
gvnimag_1 = cv2.imread('dhoni.jpg')
 
# Divide the given image with some random number using the (/) operator
# and store it in another variable
rslt_imag = gvnimag_1 /1.5
 
# Save the above result in another file using the imwrite() function 
# by passing the filename as an argument to it.
cv2.imwrite('div_image.jpg', rslt_imag)

Output:

Division of Image with a Constant

 

 

Python NULL – How to Identify Null values in Python?

NULL – How to Identify Null values in Python

Here we see, what Python null means and what the NONE type is. In various computer languages, the term ‘null‘ refers to an empty variable or a reference that points to nothing. ‘null’ is the same as ‘zero.’ In Python, however, there is no ‘null’ keyword. Instead, the object ‘None‘ is utilized for this purpose.

NULL in Python:

When a function does not have anything to return, i.e. does not have a return statement, the output is None.

In other words, the None keyword is used here to define a null variable or object. None is an object and a data type of the NoneType class.

Example

Approach:

  • Create a function say null_fun().
  • Inside the function, take a variable and initialize it with some random number.
  • Take another variable and initialize it with some random number.
  • In the main function, call the above-declared function null_fun() and print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function say null_fun()
def null_fun():
    # Inside the function, take a variable and initialize it with some random number
    num1 = 5
    # Take another variable and initialize it with some random number
    num2 = 7
# In the main function, call the above declared function null_fun() and print it
print(null_fun())

Output:

None

Explanation:

Here the function doesn't return anything hence it prints 'None' as output

Example

When we assign None to a variable, it points to the same object as all the variables that are assigned to it. There are no new instances created.

In Python, unlike in other languages, null is an object in itself, not just a synonym for 0.

type(None)

Output:

NoneType

Python Declaration of Null Variables

Python does not declare null variables by default. In other words, an undefined variable is not the same as a null variable.

Example

print(x)

Output:

Output showing an Error due to Undeclaration of Variable

Explanation:

Here the variable x is undefined, hence it raises an error

Python Code to Check whether the variable is none

We use the ‘is’ operator or the ‘==’ operator to determine whether a variable is None or not

1)Check Using ‘is’ operator:

Example

Approach:

  • Take a variable and initialize its value with None.
  • Check if the above variable value is None using the ‘is’ operator and if conditional statement.
  • If it is true, then print ‘The Output is None’.
  • Else print “The Output is not None’.
  • The Exit of the Program.

Below is the implementation:

# Take a variable and initialize its value with None
x = None
# Check if the above variable value is None using the 
# 'is' operator and if conditional statement
if x is None :
    # If it is true, then print 'The Output is None'                 
    print("The Output is None")
else :
    # Else print "The Output is not None'
    print("The Output is not None")

Output:

The Output is None

2)Check Using ‘==’ operator:

Approach:

  • Take a variable and initialize its value with None.
  • Check if the above variable value is None using the ‘==’ operator and if conditional statement.
  • If it is true, then print ‘The Output is None’.
  • Else print “The Output is not None’.
  • The Exit of the Program.

Below is the implementation:

# Take a variable and initialize its value with None
x = None
# Check if the above variable value is None using the 
# '==' operator and if conditional statement
if (x == None):
    # If it is true, then print 'The Output is None'                 
    print("The Output is None")
else :
    # Else print "The Output is not None'
    print("The Output is not None")

Output:

The Output is None

A Brief Recall

  • A null variable is defined with the None keyword.
  • None is not same as zero.
  • None as an immutable type.
  • None can be used to indicate missing values as well as default parameters.

 

Python numpy.argmax() Function with Examples

numpy.argmax() Function with Examples

Python provides us with a powerful module that allows us to work on difficult mathematical operations.

The NumPy module, which is also noted for its high level of complexity, provides us with a variety of data structures to work with. We frequently deal with data in terms of Arrays and Matrices. Analytics and preprocessing appear to be inadequate without NumPy as the mathematical model solution, whether it is a computation problem or a real-life problem.

numpy.argmax() Function:

The numpy.argmax() function returns the indices of the array’s maximum element in a particular axis.

Syntax:

numpy.argmax(array, axis = None, out = None)

Parameters

array: It is the array given as input

axis: It is an integer. This is optional. Along a specific axis, such as 0 represents along column and 1 along the row.

out: This is optional. It is an array. It provides the ability to insert output into the out array, which must be of acceptable shape and datatype.

numpy.argmax() Function with Examples in Python

1)Using argmax To Fetch Maximum Element from a Matrix

In a nutshell, the argmax() function allows us to obtain the maximum element from the entire array. However, if no axis is specified, i.e. by row or column, it just gives the number of elements at output.

Similarly, if we want to get the greatest element from the entire array without needing to provide the axis, we must use the unravel_index() function.

Approach:

  • Import numpy module using the import keyword.
  • Pass some random size(rowsize*colsize) to the arange() function and apply the reshape() function by passing arguments rowsize and column size.
  • Print the given array.
  • Apply argmax() function to the given array and pass it as an argument along with the shape of the given array to the unravel_index() function to get the index of the maximum element in the above-given matrix.
  • Store it in a variable
  • Print the above index value.
  • Print the maximum element in the given array.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random size(rowsize*colsize) to the arange() function and apply the reshape() 
# function by passing arguments rowsize and column size
gvn_arr = np.arange(16).reshape(4,4) 
# Print the given array
print("The given array\n", gvn_arr)
# Apply argmax() function to the given array and pass it as an argument along 
# with the shape of the given array to the unravel_index() function 
# to get the index of the maximum element in the above given matrix.
# Store it in a variable
print("The index of the maximum element in the above given matrix is:")
indx = np.unravel_index(np.argmax(gvn_arr), gvn_arr.shape)
# Print the above index value.
print(indx)
# Print the maximum element in the given array
print("The maximum element in the given array = ", gvn_arr[indx])

Output:

The given array
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]
 [12 13 14 15]]
The index of the maximum element in the above given matrix is:
(3, 3)
The maximum element in the given array = 15

2) Python code to fetch maximum element for a particular row

Now, we must add the argument axis=1 to the argmax() function.
As an output, this method returns the index of the maximum element across each row.

Approach:

  • Import numpy module using the import keyword.
  • Pass some random size(rowsize*colsize) to the arange() function and apply the reshape() function by passing arguments rowsize and column size.
  • Print the given array.
  • Pass the given array and axis=1 as arguments to the argmax() function to get the index of the maximum element for each row in the above-given matrix and print it.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random size(rowsize*colsize) to the arange() function and apply the reshape() 
# function by passing arguments rowsize and column size
gvn_arr = np.arange(16).reshape(4,4) 
# Print the given array
print("The given array\n", gvn_arr)
# Pass the given array and axis=1 as arguments to the argmax() function 
# to get the index of the maximum element for each row in the above given matrix
# and print it.
print("The index of the maximum element for each row in the above given matrix:")
print(np.argmax(gvn_arr, axis=1))

Output:

The given array
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]
 [12 13 14 15]]
The index of the maximum element for each row in the above given matrix:
[3 3 3 3]

3) Python code to fetch maximum element for a particular column

Now, we must add the argument axis=0 to the argmax() function.
As an output, this method returns the index of the maximum element across each column.

# Import numpy module using the import keyword
import numpy as np
# Pass some random size(rowsize*colsize) to the arange() function and apply the reshape() 
# function by passing arguments rowsize and column size
gvn_arr = np.arange(16).reshape(4,4) 
# Print the given array
print("The given array\n", gvn_arr)
# Pass the given array and axis=0 as arguments to the argmax() function 
# to get the index of the maximum element for each column in the above given matrix
# and print it.
print("The index of the maximum element for each column in the above given matrix:")
print(np.argmax(gvn_arr, axis=0))

Output:

The given array
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]
 [12 13 14 15]]
The index of the maximum element for each column in the above given matrix:
[3 3 3 3]

Python Serialize and Deserialize JSON to Objects

Serialize and Deserialize JSON to Objects

What is JSON?

JSON is an abbreviation for JavaScript Object Notation. It means that data is stored and transferred using a script (executable) file comprised of text in a computer language. Python has a built-in library named json that handles JSON. In order to use this feature, we must first load the json package into our Python script. The text in JSON is represented by a quoted-string, which contains the value in the key-value mapping within flower braces { }.

In Python, How do you serialize JSON data?

Serialization is the process of converting the raw data’s data type to JSON representation. That is to say, the raw data, which is typically a dictionary, will now match the Javascript Object Notation format.

Python provides us with the following functions to simply format our data to JSON:

  • json.dump() function
  • json.dumps() function

1)json.dump() function:

The native data of the primary data type is accepted as input by the json.dump() method. It then converts the data to JSON format and stores it in a JSON file.

Syntax:

json.dump(data, fileobject)

data: It is the actual data that needs to be converted to JSON format is referred to as data.

fileobject: This is the object that will point to the JSON file containing the transformed data. If the file does not already exist, a new file is created at the location specified by the object.

Example

Approach:

  • Import json module using the import keyword.
  • Give some random data in JSON format and store it in a variable.
  • Open some random file in write-mode using the open() function by passing the filename, mode as arguments to it.
  • Dump the given data into the above-opened file using the dump() function. It then converts the data to JSON format.
  • The Exit of the Program.

Below is the implementation:

# Import json module using the import keyword
import json
# Give some random data in Json format and store it in a variable
gvn_data= {
    "demo_data": {
        "Article By": "Btechgeeks",
         "topic": "JSON",
         "language": "Python"
    }
}
# Open some random file in write-mode using the open() function by passing
# the filename, mode as arguments to it.
with open( "demo.json" , "w" ) as d:
    # Dump the given data into the above opened file using the dump() function
    json.dump( gvn_data, d )

Output:

Raw data converted to JSON format(Output)
Raw data converted to JSON format(Output)

2)json.dumps() function

In contrast to the dump() function, the json.dumps() function converts raw data to JSON format but stores it as a string rather than pointing to a file object.

Syntax:

json.dumps(data)

Example1

Approach:

  • Import json module using the import keyword.
  • Give some random data in JSON format and store it in a variable.
  • Pass the given data as an argument to the dumps() function to convert raw data to JSON format (It stores it as a string rather than pointing to a file object).
  • Store it in a variable.
  • Print the above result

Below is the implementation:

# Import json module using the import keyword
import json
# Give some random data in Json format and store it in a variable
gvn_data= {
    "demo_data": {
        "Article By": "Btechgeeks",
         "topic": "JSON",
         "language": "Python"
    }
}
# Pass the given data as an argument to the dumps() function to convert raw data to
# JSON format.(It stores it as a string rather than pointing to a file object)
# Store it in a variable
rslt_data = json.dumps(gvn_data)
# print the above result
print(rslt_data)

Output:

{"demo_data": {"Article By": "Btechgeeks", "topic": "JSON", "language": "Python"}}

De-serialization of JSON data to Native Python Object

That is, we can simply convert JSON data into the default/native data type, which is usually a dictionary, using deserialization.

Python provides the following functions to implement the concept of de-serialization:

  • json.load() function
  • json.loads() function

json.load() Function:

We can convert JSON string data into a native dictionary object in Python using the json.load() function.

Syntax:

json.load(JSON _strdata)

Approach:

  •  Import json module using the import keyword.
  • Open the JSON file using the open() function by passing the filename/filepath
    as an argument to it and store it in a variable.
  • Pass the above JSON file data as an argument to the load() function to deserialize it.
    Store it in another variable.
  • Print the above result.
  • Print the datatype of the above result using the type() function.

Below is the implementation:

# Import json module using the import keyword
import json
# Open the JSON file using the open() function by passing the filename/filepath 
# as an argument to it and store it in a variable
file_data = open('demo.json')
# Pass the above JSON file data as an argument to the load() function to deserialize it
# Store it in another variable
rslt = json.load(file_data)
# Print the above result
print(rslt)
# Print the datatype of the above result using the type() function.
print("After de-serialization, the datatype of the above result is:\n", type(rslt))

Output:

{'demo_data': {'Article By': 'Btechgeeks', 'topic': 'JSON', 'language': 'Python'}}
After de-serialization, the datatype of the above result is:
<class 'dict'>

Here, we first used the open() function to load the JSON file. Following that, we give the object corresponding to the JSON file to the load() function, where it is deserialized into dictionary form.

Python Numpy vstack() Method with Examples

Numpy vstack() Method with Examples

Numpy.vstack() Method in Python:

Numpy.vstack() is a Python function that concatenates a tuple of arrays vertically along the first dimension to create a single array.

To build a single array, it stacks the sequence of input arrays vertically.

Syntax:

numpy.vstack(tuple)

Parameters

tuple: It is the sequence of ndarrays that we want to concatenate. Except for the first axis, the arrays must have the same shape along all axis.

Return Value: 

It returns a stacked ndarray i.e, the stacked array of the input arrays.

Numpy vstack() Method with Examples in Python

Example1

Approach:

  • Import numpy module using the import keyword.
  • Give the first array as static input using the array() function and store it in a variable.
  • Give the second array as static input using the array() function and store it in another variable.
  • Give the third array as static input using the array() function and store it in another variable.
  • Print the dimensions/shape of the above given 3 arrays using the shape function.
  • Pass the above given 3 arrays as arguments to the vstack() function to get a vertically stacked 2-D array.
  • Store it in another variable.
  • Print the shape of the above stack array using the shape function.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy
# Give the first array as static input using the array() function
# and store it in a variable
gvn_arry1= numpy.array([4, 6, 1, 9])
# Give the second array as static input using the array() function and
# store it in another variable
gvn_arry2 = numpy.array([2, 3, 1, 14])
# Give the third array as static input using the array() function and 
# store it in another variable
gvn_arry3 = numpy.array([8, 5, 4, 9])
# Print the dimensions/shape of the above given 3 arrays using the shape function
print("Given First array shape is:", gvn_arry1.shape)
print("Given second array shape is:", gvn_arry2.shape)
print("Given third array shape is:", gvn_arry3.shape)
print()
# Pass the above given 3 arrays as arguments to the vstack() function
# to get a vertically stacked 2-D array.
# store it in another variable
stack_arry = numpy.vstack((gvn_arry1, gvn_arry2, gvn_arry3))
print("The Stacked array for the above given 3 arrays is:")
print(stack_arry)
# Print the shape of the above stack array using the shape function
print("The result stacked array shape is:", stack_arry.shape)

Output:

Given First array shape is: (4,)
Given second array shape is: (4,)
Given third array shape is: (4,)

The Stacked array for the above given 3 arrays is:
[[ 4 6 1 9]
 [ 2 3 1 14]
 [ 8 5 4  9]]
The result stacked array shape is: (3, 4)

Example2: The arrays are stacked along the first dimensions for N-Dimensional arrays

# Import numpy module using the import keyword
import numpy
# Give the first array(2D) as static input using the array() function
# and store it in a variable
gvn_arry1= numpy.array([ [10, 5, 1], [2, 7, 3] ])
# Give the second array(2D) as static input using the array() function and
# store it in another variable
gvn_arry2 = numpy.array([ [4, 1, 6], [1, 8, 9] ])
# Print the dimensions/shape of the above given two 2D arrays using the shape function
print("Given First array shape is:", gvn_arry1.shape)
print("Given second array shape is:", gvn_arry2.shape)
print()
# Pass the above given 2 arrays as arguments to the vstack() function
# to get a vertically stacked array.
# store it in another variable
stack_arry = numpy.vstack((gvn_arry1, gvn_arry2))
print("The Stacked array for the above given two 2D arrays is:")
print(stack_arry)
# Print the shape of the above stack array using the shape function
print("The result stacked array shape is:", stack_arry.shape)

Output:

Given First array shape is: (2, 3)
Given second array shape is: (2, 3)

The Stacked array for the above given two 2D arrays is:
[[10 5 1]
 [ 2 7 3]
 [ 4 1 6]
 [ 1 8 9]]
The result stacked array shape is: (4, 3)

The shape of N-dimensional arrays must be the same along all dimensions except the first, as seen below:

Example3

# Import numpy module using the import keyword
import numpy
# Give the first array as static input using the array() function
# and store it in a variable
gvn_arry1= numpy.array([ [10, 5], [2, 7] ])
# Give the second array as static input using the array() function and
# store it in another variable
gvn_arry2 = numpy.array([ [4, 1], [1, 9], [6, 5]])
# Print the dimensions/shape of the above given two arrays using the shape function
print("Given First array shape is:", gvn_arry1.shape)
print("Given second array shape is:", gvn_arry2.shape)
print()
# Pass the above given 2 arrays as arguments to the vstack() function
# to get a vertically stacked array.
# store it in another variable
stack_arry = numpy.vstack((gvn_arry1, gvn_arry2))
print("The Stacked array for the above given two arrays is:")
print(stack_arry)
# Print the shape of the above stack array using the shape function
print("The result stacked array shape is:", stack_arry.shape)

Output:

Given First array shape is: (2, 2)
Given second array shape is: (3, 2)

The Stacked array for the above given two arrays is:
[[10 5]
 [ 2 7]
 [ 4 1]
 [ 1 9]
 [ 6 5]]
The result stacked array shape is: (5, 2)

 

 

BLEU Score in Python and Its Implementation

BLEU Score in Python and Its Implementation

In Python, the BLEU score is a metric that measures the quality of Machine Translation models. Though it was actually planned exclusively for translation models, it is now used for various natural language processing applications.

The BLEU score compares a sentence to one or more reference sentences and indicates how well the candidate sentence matched the list of reference sentences. It returns a score between 0 and 1.

Python BLEU score Calculation

We’ll use the NLTK module, which includes the sentence_bleu() function, to implement the BLEU score. It allows us to pass the reference sentences as well as the candidate sentence. The candidate sentence is then compared to the reference sentences.

If a perfect match is found, the BLEU score is returned as 1. If there is no match, it returns 0. The BLUE score for a half/partial match will be between 0 and 1.

Implementation

Example

Approach:

  • Import sentence_bleu function from nltk.translate.bleu_score module using the import keyword.
  • Create a list of lists in which each list contains words of a sentence (here split() function will separate the words from the sentence).
  • Take some random sentence and get all the words of it using the split() function.
  • Pass the above list of lists and the above-tested list for the sentence_bleu() function and print the BLEU score of it.
  • Similarly, do the same for the other (here both the data and tested list are fully matched. hence it returns 1 ).
  • The Exit of the Program.

Below is the implementation:

# Import sentence_bleu function from nltk.translate.bleu_score module using the import keyword
from nltk.translate.bleu_score import sentence_bleu
# Create a list of lists in which each list contains words of a sentence 
# (here split() function will separate the words from the sentence)
gvn_data = [
    'hello this is btechgeeks'.split(),
    'good morning btechgeeks'.split(),
    'welcome to btechgeeks'.split()
]
# Take some random sentence and get all the words of it using the split() function
testd_lst1 = 'good is btechgeeks'.split()
# Pass the above list of lists and the above tested list for the sentence_bleu() function
# and print the BLEU score of it.
print('The above tested list1 BLEU score= ',sentence_bleu(gvn_data, testd_lst1))
# Similarly, do the same for the other.
# (here both the data and tested list are fully matched. hence it returns 1 ) 
testd_lst2 = 'hello this is btechgeeks'.split()
print('The above tested list2 BLEU score= ', sentence_bleu(gvn_data, testd_lst2))

Output:

The above tested list1 BLEU score= 0.8408964152537145
The above tested list2 BLEU score= 1.0

N-gram Score Calculation

When matching sentences, you can specify how many words the model should match at once. For example, you can specify that words be matched one at a time (1-gram). You may also match words in pairs (2-gram) or triplets (3-gram) (3-grams).

This section will teach you how to compute these n-gram scores.

You can supply an argument with weights equivalent to individual grams to the sentence_bleu() method.

1-gram: (1, 0, 0, 0)
2-gram: (0, 1, 0, 0) 
3-gram: (1, 0, 1, 0)
4-gram: (0, 0, 0, 1)

Example

Approach:

  • Import sentence_bleu function from nltk.translate.bleu_score module using the import keyword.
  • Create a list of lists in which each list contains words of a sentence (here split() function will separate the words from the sentence).
  • Take some random sentence and get all the words of it using the split() function.
  • Pass the above list of lists and the above-tested list, 2-gram weights for the sentence_bleu() function, and print the BLEU score of it.
  • The Exit of the Program.

Below is the implementation:

# Import sentence_bleu function from nltk.translate.bleu_score module using the import keyword
from nltk.translate.bleu_score import sentence_bleu
# Create a list of lists in which each each list contain words of a sentence 
# (here split() function will separate the words from the sentence)
gvn_data = [
    'hello this is btechgeeks'.split(),
    'good morning btechgeeks'.split(),
    'welcome to btechgeeks'.split()
]
# Take some random sentence and get all the words of it using the split() function
testd_lst1 = 'good is btechgeeks'.split()
# Pass the above list of lists and the above tested list, 2-gram weights for the 
# sentence_bleu() function and print the BLEU score of it.
print('The above tested list1 BLEU score(2-gram)= ', sentence_bleu(gvn_data, testd_lst1, weights=(0, 1, 0, 0)))

Output:

The above tested list1 BLEU score(2-gram)= 0.5

Melt and Unmelt Data using Pandas melt() and pivot() Function

Melt and Unmelt Data using Pandas melt() and pivot() Function

This tutorial will go through how to use the melt() and pivot() functions to melt and unmelt data values in a Pandas data frame.

Pandas Melting and Unmelting data

Before delving into the topic of melting and unmelting data, I’d like to draw your attention to this enticing word: Ice-Cream.
Yes! Ice-cream… When you’ve got it on your plate and you get a call just as you’re ready to take the first bite. Obviously, the ice cream will melt and turn into a milkshake.

Consider the concept of Melting data values in a data frame, which is comparable. Data value melting is used to customize and change data values from a wider format to a more restricted and long format. The primary goal of Melting is to generate a specific format of Dataframe in which one or more data columns serve as identifiers for the data attributes.

In this case, the remaining data variables are treated as data values, and there are only two columns: variable and value.

Unmelting, on the other hand, is performed on the data variables to return the values to their original format.

After we’ve covered Melting and Unmelting data, let’s look at the Pandas functions that allow us to do the same.

Pandas Module

Pandas is a Python-based open-source library with a BSD license. Pandas offer high-performance, quick, and simple data structures and data analysis tools for manipulating numeric data and time series. Pandas is based on the Numpy library and is developed in Python, Cython, and C. Wes McKinney created the Pandas library in 2008. Data can be imported into Pandas from a variety of file types, including JSON, SQL, Microsoft Excel, and others. The dataframes functionality is used to load data and manipulate it.

To perform analysis more effectively, we may need to restructure the Pandas data frame. In data analysis, reshaping is critical. Pandas offer reshaping functions such as melt() and unmelt().

Pandas melt() Function

The melt() function in Pandas is used to convert the DataFrame format from wide to long. It is used to generate a special DataFrame object structure in which one or more columns serve as Identifiers. The remaining columns are all handled as values and are unpivoted to the row axis, leaving only two columns: variable and value.

Syntax:

pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value')

Parameters

frame: It is the actual dataframe to be melted.
id_vars: Names of columns that will be used as identifiers.
value_vars: All variable names that will be transformed into values (other than the identifier variables).
value_name: The name of the column value, which is the default.

Example

Approach:

  • Import pandas module using the import keyword.
  • Give some random data in JSON format and store it in a variable.
  • Pass the above data to pandas.DataFrame() function to convert it into a dataframe.
  • Print the above data frame before melting.
  • Pass the dataframe, Rollno as id_vars and “Names”, “Marks” as value_vars as the argument to the melt() function and to return the dataframe from wide to a longer format.
  • Print the above data frame after melting.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword
import pandas as pd
# Give some random data in Json format and store it in a variable
gvn_data = {"Names": ["Nick", "July", "Alex","Jhon"], "Rollno": [1, 2, 3, 4], "Marks": [75, 54, 90, 86]}
# Pass the above data to pandas.DataFrame() function to convert it into a dataframe
rslt_datafrme = pd.DataFrame(gvn_data)
# Print the above data frame before melting
print("The above data before melting:")
print(rslt_datafrme)
print()
# Pass the dataframe, Rollno as id_vars and "Names", "Marks" as value_vars as the argument to the
# melt() function and to return the dataframe from wide to a longer format
datafrme_meltd = pd.melt(rslt_datafrme, id_vars=["Rollno"], value_vars=["Names", "Marks"])
# Print the above data frame after melting
print("The above data after melting:")
print(datafrme_meltd)

Output:

The above data before melting:
  Names  Rollno  Marks
0  Nick       1     75
1  July       2     54
2  Alex       3     90
3  Jhon       4     86

The above data after melting:
   Rollno variable value
0       1    Names  Nick
1       2    Names  July
2       3    Names  Alex
3       4    Names  Jhon
4       1    Marks    75
5       2    Marks    54
6       3    Marks    90
7       4    Marks    86

Pandas unmelt() Function

The pivot() function can be used to unmelt a DataFrame object and retrieve the original dataframe. The ‘index’ argument value of the pivot() function should be the same as the ‘id vars’ value. The value of ‘columns’ should be used as the name of the ‘variable’ column.

Syntax:

pandas.pivot(index, columns)

Parameters

index: Labels that must be applied in order for the new data frame’s index in place.
columns: Labels that must be applied in order for the new data frame’s columns in place.

Example

Approach:

  • Import pandas module using the import keyword.
  • Give some random data in JSON format and store it in a variable.
  • Pass the above data to pandas.DataFrame() function to convert it into a dataframe and store it in another variable.
  • Print the above data frame before melting.
  • Pass the dataframe, Rollno as id_vars and “Names”, “Marks” as value_vars, var_name=”Expression”, value_name=”Value” that represets the unpivoted variables as the arguments to the melt() function to return the dataframe from wide to a longer format.
  • Print the above data frame after melting.
  • Apply pivot() function on the above-melted dataframe by passing index as ‘Rollno’ and columns as ‘Expression’ as the arguments to it.
  • Store it in another variable.
  • Print the above data after unmelting.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword
import pandas as pd
# Give some random data in Json format and store it in a variable
gvn_data = {"Names": ["Nick", "July", "Alex","Jhon"], "Rollno": [1, 2, 3, 4], "Marks": [75, 54, 90, 86]}
# Pass the avove data to pandas.DataFrame() function to convert it into a dataframe
rslt_datafrme = pd.DataFrame(gvn_data)
# Print the above data frame before melting
print("The above data before melting:")
print(rslt_datafrme)
print()
# Pass the dataframe, Rollno as id_vars and "Names", "Marks" as value_vars, var_name="Expression", 
# value_name="Value" that represets the unpivoted variables as the arguments to the melt() function
# to return the dataframe from wide to a longer format
datafrme_meltd = pd.melt(rslt_datafrme, id_vars=["Rollno"], value_vars=["Names", "Marks"], var_name="Expression", value_name="Value")
# Print the above data frame after melting
print("The above data after melting:")
print(datafrme_meltd)
print()
# Apply pivot() function on the above melted dataframe by passing index as 'Rollno'
# and columns as 'Expression' as the arguments to it.
# Store it in another variable.
datafrme_unmeltd = datafrme_meltd.pivot(index='Rollno', columns='Expression')
# Print the above data after unmelting
print("The above data after unmelting:")
print(datafrme_unmeltd)

Output:

The above data before melting:
  Names  Rollno  Marks
0  Nick       1     75
1  July       2     54
2  Alex       3     90
3  Jhon       4     86

The above data after melting:
   Rollno Expression Value
0       1      Names  Nick
1       2      Names  July
2       3      Names  Alex
3       4      Names  Jhon
4       1      Marks    75
5       2      Marks    54
6       3      Marks    90
7       4      Marks    86

The above data after unmelting:
           Value      
Expression Marks Names
Rollno                
1             75  Nick
2             54  July
3             90  Alex
4             86  Jhon