Python Program to Check whether all Digits of a Number Divide it

Program to Check whether all Digits of a Number Divide it

Using a Python program, we will learn how to check whether all of the digits in a number divide it. We’ll divide the given number by each digit to see if it’s divisible. So you’ll learn how to retrieve a number’s individual digits, a method to check whether the number is divisible by its digits, and a Python program to do so.

Examples:

Example1:

Input:

Given Number =144

Output:

The given number [ 144 ] all the digits of the given number divides the given number

Example2:

Input:

Given Number =369

Output:

The given number [ 369 ] all the digits of the given number do not divide the given number

Program to Check whether all Digits of a Number Divide it in Python

Below are the ways to check whether all the digits of the given number divide it using Python

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Create a function checkdivide() which takes the given number as an argument and returns true if all the digits of the given number divide it else it returns false.
  • Pass the given number as an argument to checkdivide() function.
  • Inside the checkdivide() function.
  • Convert the given number into list of digits using list(),map(),int() and split() functions.
  • Loop in this digits list using For loop.
  • Inside the For loop check whether the given number is divisible by the iterator(digit).
  • If it is false then return False.
  • After the end of for loop return True.
  • Check if the functions return true or false using the If conditional Statement.
  • If it is true then print all the digits of the given number divides the given number.
  • Else print all the digits of the given number do not divide the given number.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkdivide() which takes the given number
# as an argument and returns true if all the digits of the given number
# divide it else it returns false.


def checkdivide(gvnnumb):
    # Inside the checkdivide() function.
    # Convert the given number into list of digits
    # using list(),map(),int() and split() functions.
    digitslstt = list(map(int, str(gvnnumb)))
    # Loop in this digits list using For loop.
    for digt in digitslstt:
        # Inside the For loop check whether the given number
        # is divisible by the iterator(digit).
        # If it is false then return False.
        if(gvnnumb % digt != 0):
            return False
    # After the end of for loop return True.
    return True


# Give the number as static input and store it in a variable.
numb = 144

# Pass the given number as an argument to checkdivide() function.
# Check if the functions return true or false using the If conditional Statement.
if(checkdivide(numb)):
        # If it is true then print all the digits of
        # the given number divides the given number.
    print('The given number [', numb,
          '] all the digits of the given number divides the given number')
# Else print all the digits of the given number do not divide the given number.
else:
    print('The given number [', numb,
          '] all the digits of the given number do not divide the given number')

Output:

The given number [ 144 ] all the digits of the given number divides the given number

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Create a function checkdivide() which takes the given number as an argument and returns true if all the digits of the given number divide it else it returns false.
  • Pass the given number as an argument to checkdivide() function.
  • Inside the checkdivide() function.
  • Convert the given number into list of digits using list(),map(),int() and split() functions.
  • Loop in this digits list using For loop.
  • Inside the For loop check whether the given number is divisible by the iterator(digit).
  • If it is false then return False.
  • After the end of for loop return True.
  • Check if the functions return true or false using the If conditional Statement.
  • If it is true then print all the digits of the given number divides the given number.
  • Else print all the digits of the given number do not divide the given number.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkdivide() which takes the given number
# as an argument and returns true if all the digits of the given number
# divide it else it returns false.


def checkdivide(gvnnumb):
    # Inside the checkdivide() function.
    # Convert the given number into list of digits
    # using list(),map(),int() and split() functions.
    digitslstt = list(map(int, str(gvnnumb)))
    # Loop in this digits list using For loop.
    for digt in digitslstt:
        # Inside the For loop check whether the given number
        # is divisible by the iterator(digit).
        # If it is false then return False.
        if(gvnnumb % digt != 0):
            return False
    # After the end of for loop return True.
    return True


# Give the number as user input using the int(input()) function
# and store it in a variable.
numb = int(input('Enter some random number = '))

# Pass the given number as an argument to checkdivide() function.
# Check if the functions return true or false using the If conditional Statement.
if(checkdivide(numb)):
        # If it is true then print all the digits of
        # the given number divides the given number.
    print('The given number [', numb,
          '] all the digits of the given number divides the given number')
# Else print all the digits of the given number do not divide the given number.
else:
    print('The given number [', numb,
          '] all the digits of the given number do not divide the given number')

Output:

Enter some random number = 369
The given number [ 369 ] all the digits of the given number do not divide the given number

The digit 6 does not divide the given number so it returns False.
Related Programs:

Python Program to Find the Least Frequent Character in a String

Program to Find the Least Frequent Character in a String

Give the string the task is to print the least frequent character in a string in Python.

Examples:

Example1:

Input:

Given string =zzzyyddddeeeee

Output:

The least frequency character in the given string zzzyyddddeeeee is [ y ]

Example2:

Input:

Given string =btechgeeks

Output:

The least frequency character in the given string btechgeeks is [ b ]

Program to Find the Least Frequent Character in a String in Python

Below are the ways to print the least frequent character in a string in Python.

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

Method #1: Using Counter() (Hashing , Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string a static input and store it in a variable.
  • Calculate the frequency of all the given string elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say elementsfrequency)
  • Calculate the minimum frequency character in the given string using the min() and “get” function and store it in a variable.
  • Print the least frequency character in the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the string a static input and store it in a variable.
gvnstrng = 'zzzyyddddeeeee'
# Calculate the frequency of all the given string elements
# using the Counter() function which returns the element
# and its frequency as key-value pair and store this
# dictionary in a variable(say elementsfrequency)
elementsfrequency = Counter(gvnstrng)
# Calculate the minimum frequency character in the given string
# using the min() and "get" function and store it in a variable.
minfreqchar = str(min(elementsfrequency, key=elementsfrequency.get))
# Print the least frequency character in the given string
# by printing the above variable.
print('The least frequency character in the given string',
      gvnstrng, 'is [', minfreqchar, ']')

Output:

The least frequency character in the given string zzzyyddddeeeee is [ y ]

Method #2: Using Counter() (Hashing , User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string a user input using the input() function and store it in a variable.
  • Calculate the frequency of all the given string elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say elementsfrequency)
  • Calculate the minimum frequency character in the given string using the min() and “get” function and store it in a variable.
  • Print the least frequency character in the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the string a static input and store it in a variable.
gvnstrng = input('Enter some random string = ')
# Calculate the frequency of all the given string elements
# using the Counter() function which returns the element
# and its frequency as key-value pair and store this
# dictionary in a variable(say elementsfrequency)
elementsfrequency = Counter(gvnstrng)
# Calculate the minimum frequency character in the given string
# using the min() and "get" function and store it in a variable.
minfreqchar = str(min(elementsfrequency, key=elementsfrequency.get))
# Print the least frequency character in the given string
# by printing the above variable.
print('The least frequency character in the given string',
      gvnstrng, 'is [', minfreqchar, ']')

Output:

Enter some random string = btechgeeks
The least frequency character in the given string btechgeeks is [ b ]

Related Programs:

Python Pandas Series ge() Function

Python Pandas Series ge() Function

Pandas Series ge() Function:

The ge() function of the Pandas module compares series and other, element-by-element, for greater than equal to and returns the outcome of the comparison. It is comparable to series >= other, but with the ability to use a fill_value as one of the parameters to replace missing data.

Syntax:

Series.ge(other, level=None, fill_value=None, axis=0)

Parameters

other: This is required. It indicates a Series or a scalar value.

level: This is optional. To broadcast over a level, specify an int or a name that matches the Index values on the passed MultiIndex level. The type of this may be int or name. None is the default value.

fill_value: This is optional. It indicates a value to fill in any current missing (NaN) values, as well as any new elements required for successful Series alignment. The result will be missing if data is missing in both corresponding Series locations. The type of this may be float or None. None is the default value.

axis:  This is optional. To apply the method by rows, use 0 or ‘index,’ and to apply it by columns, use 1 or ‘columns.’

Return Value:

The result of the comparison i.e, a boolean series is returned.

Pandas Series ge() Function in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Pass some random list as an argument to the Series() function of the pandas module to create a series.
  • Store it in a variable.
  • Print the above-given series.
  • Apply ge() function on all the elements of the given series by passing some random number to it and print the result.
  • Here it compares if all the elements of the given series are >= 40
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random list as an argument to the Series() function
# of the pandas module to create a series.
# Store it in a variable.
gvn_series = pd.Series([12, 25, 65, 40, 100])
# Print the above given series
print("The given series is:")
print(gvn_series)
print()
# Apply ge() function on all the elements of the given series
# by passing some random number to it and print the result.
# Here it compares if all the elements of the given series are >= 40
print("Checking if all the elements of the given series are >= 40:")
print(gvn_series.ge(40))

Output:

The given series is:
0     12
1     25
2     65
3     40
4    100
dtype: int64

Checking if all the elements of the given series are >= 40:
0    False
1    False
2     True
3     True
4     True
dtype: bool

Example2

Approach:

  • Import pandas module using the import keyword.
  • Import numpy module using the import keyword.
  • Pass some random list, index values as the arguments to the Series() function of the pandas module to create the first series and store it in a variable.
  • Pass some random list, index values as the arguments to the Series() function of the pandas module to create the second series and store it in another variable.
  • Print the given first series
  • Print the given second series
  • Pass the above second series, fill_value as the arguments to the ge() function and apply it on the first series to check for the greater than or equal to(>=)condition and print the result.
  • Here it compares the elements of the first series >= second series by replacing NaN values with 10.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Import numpy module using the import keyword.
import numpy as np
# Pass some random list, index values as the arguments to the Series() function
# of the pandas module to create the  first series and store it in a variable.
fst_series = pd.Series([13, 25, np.NaN, 80, 70], 
              index=['P', 'Q', 'R', 'S', 'T'])
# Pass some random list, index values as the arguments to the Series() function
# of the pandas module to create the second series and store it in another variable.
scnd_series = pd.Series([9, 35, 15, 20,  np.NaN], 
              index=['P', 'Q', 'R', 'S', 'T'])

# Print the given first series
print("The given first series is:")
print(fst_series)
print()
# Print the given second series
print("The given second series is:")
print(scnd_series)
print()
# Pass the above second series, fill_value as the arguments to the ge() function 
# and apply it on the first series to check for the greater than or equal to(>=)
# condition and print the result.
# Here it compares if the elements of the first series >= second series by repalcing 
# NaN values with 10
print("Comparing if the elements of the first series >= second series:")
print(fst_series.ge(scnd_series, fill_value = 10))

Output:

The given first series is:
P    13.0
Q    25.0
R     NaN
S    80.0
T    70.0
dtype: float64

The given second series is:
P     9.0
Q    35.0
R    15.0
S    20.0
T     NaN
dtype: float64

Comparing if the elements of the first series >= second series:
P     True
Q    False
R    False
S     True
T     True
dtype: bool

Example3

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary) as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe.
  • Compare both the columns gvn_list1 and gvn_list2 using the ge() function and store the result as a new column in the dataframe.
  • Here it checks if gvn_list1 >= gvn_list2 element-wise.
  • Print the dataframe after adding a new column(gvn_list1 >= gvn_list2).
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary) as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme  = pd.DataFrame({
  "gvn_list1": [45, 24, 54, 90],
  "gvn_list2": [55, 7, 54, 44]
})
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Compare both the columns gvn_list1 and gvn_list2 using the ge() function
# and store the result as a new column in the dataframe.
# Here it checks if gvn_list1 >= gvn_list2 element-wise.
data_frme ['gvn_list1 >= gvn_list2'] = data_frme ['gvn_list1'].ge(data_frme ['gvn_list2'])
# Print the dataframe after adding a new column(gvn_list1 >= gvn_list2)
print("The dataframe after adding a new column(gvn_list1 >= gvn_list2):")
print(data_frme )

Output:

The given Dataframe:
   gvn_list1  gvn_list2
0         45         55
1         24          7
2         54         54
3         90         44

The dataframe after adding a new column(gvn_list1 >= gvn_list2):
   gvn_list1  gvn_list2  gvn_list1 >= gvn_list2
0         45         55                   False
1         24          7                    True
2         54         54                    True
3         90         44                    True

 

Python Pandas Series eq() Function

Python Pandas Series eq() Function

Pandas Series eq() Function:

The eq() function of the Pandas module compares series and other elements for equal to and returns the outcome of the comparison. It is equivalent to series == other, but with the ability to provide a fill value as one of the parameters to replace missing data.

Syntax:

Series.eq(other, level=None, fill_value=None)

Parameters

other: This is required. It indicates a Series or a scalar value.

level: This is optional. To broadcast over a level, specify an int or a name that matches the Index values on the passed MultiIndex level. The type of this may be int or name. None is the default value.

fill_value: This is optional. It indicates a value to fill in any current missing (NaN) values, as well as any new elements required for successful Series alignment. The result will be missing if data is missing in both corresponding Series locations. The type of this may be float or None. None is the default value.

Return Value:

The result of the comparison i.e, a boolean series is returned.

Pandas Series eq() Function in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Pass some random list as an argument to the Series() function of the pandas module to create a series.
  • Store it in a variable.
  • Print the above-given series.
  • Apply eq() function on all the elements of the given series by passing some random number to it and print the result.
  • Here it compares if all the elements of the given series are == 40
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random list as an argument to the Series() function
# of the pandas module to create a series.
# Store it in a variable.
gvn_series = pd.Series([12, 40, 65, 40, 100])
# Print the above given series
print("The given series is:")
print(gvn_series)
print()
# Apply eq() function on all the elements of the given series
# by passing some random number to it and print the result.
# Here it compares if all the elements of the given series == 40
print("Checking if all the elements of the given series are == 40:")
print(gvn_series.eq(40))

Output:

The given series is:
0     12
1     40
2     65
3     40
4    100
dtype: int64

Checking if all the elements of the given series are == 40:
0    False
1     True
2    False
3     True
4    False
dtype: bool

Example2

Approach:

  • Import pandas module using the import keyword.
  • Import numpy module using the import keyword.
  • Pass some random list, index values as the arguments to the Series() function of the pandas module to create the first series and store it in a variable.
  • Pass some random list, index values as the arguments to the Series() function of the pandas module to create the second series and store it in another variable.
  • Print the given first series
  • Print the given second series
  • Pass the above second series, fill_value as the arguments to the eq() function and apply it on the first series to check for the equal to(==) condition and print the result.
  • Here it compares if the elements of the first series == second series by replacing NaN values with 10
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Import numpy module using the import keyword.
import numpy as np
# Pass some random list, index values as the arguments to the Series() function
# of the pandas module to create the  first series and store it in a variable.
fst_series = pd.Series([13, 25, np.NaN, 20, 70], 
              index=['P', 'Q', 'R', 'S', 'T'])
# Pass some random list, index values as the arguments to the Series() function
# of the pandas module to create the second series and store it in another variable.
scnd_series = pd.Series([9, 25, 10, 20,  np.NaN], 
              index=['P', 'Q', 'R', 'S', 'T'])

# Print the given first series
print("The given first series is:")
print(fst_series)
print()
# Print the given second series
print("The given second series is:")
print(scnd_series)
print()
# Pass the above second series, fill_value as the arguments to the eq() function 
# and apply it on the first series to check for the equal to(==) condition 
# and print the result.
# Here it compares if the elements of the first series == second series by replacing 
# NaN values with 10
print("Comparing if the elements of the first series == second series:")
print(fst_series.eq(scnd_series, fill_value = 10))

Output:

The given first series is:
P    13.0
Q    25.0
R     NaN
S    20.0
T    70.0
dtype: float64

The given second series is:
P     9.0
Q    25.0
R    10.0
S    20.0
T     NaN
dtype: float64

Comparing if the elements of the first series == second series:
P    False
Q     True
R     True
S     True
T    False
dtype: bool

Example3

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary) as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe.
  • Compare both the columns gvn_list1 and gvn_list2 using the eq() function and store the result as a new column in the dataframe.
  • Here it checks if gvn_list1 == gvn_list2 element-wise.
  • Print the dataframe after adding a new column(gvn_list1 == gvn_list2).
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary) as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme  = pd.DataFrame({
  "gvn_list1": [45, 24, 54, 90],
  "gvn_list2": [45, 7, 54, 44]
})
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Compare both the columns gvn_list1 and gvn_list2 using the eq() function
# and store the result as a new column in the dataframe.
# Here it checks if gvn_list1 == gvn_list2 element-wise.
data_frme ['gvn_list1 == gvn_list2'] = data_frme ['gvn_list1'].eq(data_frme ['gvn_list2'])
# Print the dataframe after adding a new column(gvn_list1 == gvn_list2)
print("The dataframe after adding a new column(gvn_list1 == gvn_list2):")
print(data_frme )

Output:

The given Dataframe:
   gvn_list1  gvn_list2
0         45         45
1         24          7
2         54         54
3         90         44

The dataframe after adding a new column(gvn_list1 == gvn_list2):
   gvn_list1  gvn_list2  gvn_list1 == gvn_list2
0         45         45                    True
1         24          7                   False
2         54         54                    True
3         90         44                   False

 

Python Pandas Series ne() Function

Python Pandas Series ne() Function

Pandas Series ne() Function:

The ne() function of the Pandas module compares series and other, element-by-element, for not equal to and returns the outcome of the comparison. It is equivalent to series!= other, but with the ability to provide a fill_value as one of the parameters to replace missing data.

Syntax:

Series.ne(other,  level=None,  fill_value=None)

Parameters

other: This is required. It indicates a Series or a scalar value.

level: This is optional. To broadcast over a level, specify an int or a name that matches the Index values on the passed MultiIndex level. The type of this may be int or name. None is the default value.

fill_value: This is optional. It indicates a value to fill in any current missing (NaN) values, as well as any new elements required for successful Series alignment. The result will be missing if data is missing in both corresponding Series locations. The type of this may be float or None. None is the default value.

Return Value:

The result of the comparison i.e, a boolean series is returned.

Pandas Series ne() Function in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Pass some random list as an argument to the Series() function of the pandas module to create a series.
  • Store it in a variable.
  • Print the above-given series.
  • Apply ne() function on all the elements of the given series by passing some random number to it and print the result.
  • Here it compares if all the elements of the given series are != 40 (not equal to 40)
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random list as an argument to the Series() function
# of the pandas module to create a series.
# Store it in a variable.
gvn_series = pd.Series([12, 40, 65, 40, 100])
# Print the above given series
print("The given series is:")
print(gvn_series)
print()
# Apply ne() function on all the elements of the given series
# by passing some random number to it and print the result.
# Here it compares if all the elements of the given series != 40
print("Checking if all the elements of the given series are != 40:")
print(gvn_series.ne(40))

Output:

The given series is:
0     12
1     40
2     65
3     40
4    100
dtype: int64

Checking if all the elements of the given series are != 40:
0     True
1    False
2     True
3    False
4     True
dtype: bool

Example2

Approach:

  • Import pandas module using the import keyword.
  • Import numpy module using the import keyword.
  • Pass some random list, index values as the arguments to the Series() function of the pandas module to create the first series and store it in a variable.
  • Pass some random list, index values as the arguments to the Series() function of the pandas module to create the second series and store it in another variable.
  • Print the given first series
  • Print the given second series
  • Pass the above second series, fill_value as the arguments to the ne() function and apply it on the first series to check for the NOT equal to(!=) condition and print the result.
  • Here it compares if the elements of the first series != second series by replacing NaN values with 10
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Import numpy module using the import keyword.
import numpy as np
# Pass some random list, index values as the arguments to the Series() function
# of the pandas module to create the  first series and store it in a variable.
fst_series = pd.Series([13, 25, np.NaN, 20, 70], 
              index=['P', 'Q', 'R', 'S', 'T'])
# Pass some random list, index values as the arguments to the Series() function
# of the pandas module to create the second series and store it in another variable.
scnd_series = pd.Series([9, 25, 10, 20,  np.NaN], 
              index=['P', 'Q', 'R', 'S', 'T'])

# Print the given first series
print("The given first series is:")
print(fst_series)
print()
# Print the given second series
print("The given second series is:")
print(scnd_series)
print()
# Pass the above second series, fill_value as the arguments to the ne() function 
# and apply it on the first series to check for the NOT equal to(!=) condition 
# and print the result.
# Here it compares if the elements of the first series != second series by replacing 
# NaN values with 10
print("Comparing if the elements of the first series != second series:")
print(fst_series.ne(scnd_series, fill_value = 10))

Output:

The given first series is:
P    13.0
Q    25.0
R     NaN
S    20.0
T    70.0
dtype: float64

The given second series is:
P     9.0
Q    25.0
R    10.0
S    20.0
T     NaN
dtype: float64

Comparing if the elements of the first series != second series:
P     True
Q    False
R    False
S    False
T     True
dtype: bool

Example3

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary) as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe.
  • Compare both the columns gvn_list1 and gvn_list2 using the ne() function and store the result as a new column in the dataframe.
  • Here it checks if gvn_list1 != gvn_list2 (not equal to) element-wise.
  • Print the dataframe after adding a new column(gvn_list1 != gvn_list2).
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary) as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme  = pd.DataFrame({
  "gvn_list1": [45, 24, 54, 90],
  "gvn_list2": [45, 7, 54, 44]
})
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Compare both the columns gvn_list1 and gvn_list2 using the ne() function
# and store the result as a new column in the dataframe.
# Here it checks if gvn_list1 != gvn_list2(not equal to) element-wise.
data_frme ['gvn_list1 != gvn_list2'] = data_frme ['gvn_list1'].ne(data_frme ['gvn_list2'])
# Print the dataframe after adding a new column(gvn_list1 != gvn_list2)
print("The dataframe after adding a new column(gvn_list1 != gvn_list2):")
print(data_frme )

Output:

The given Dataframe:
   gvn_list1  gvn_list2
0         45         45
1         24          7
2         54         54
3         90         44

The dataframe after adding a new column(gvn_list1 != gvn_list2):
   gvn_list1  gvn_list2  gvn_list1 != gvn_list2
0         45         45                   False
1         24          7                    True
2         54         54                   False
3         90         44                    True

 

Python Pandas Series cov() Function

Python Pandas Series cov() Function

Pandas Series cov() Function:

The cov() function of the Pandas Series calculates the covariance of a Series with other Series, ignoring missing values. The computation automatically excludes both NA and null values.

Syntax:

Series.cov(other, min_periods=None, ddof=1)

Parameters

other: This is required. It indicates a Series for which the covariance has to be computed.

min_periods: This is optional. It is an int that indicates the minimum number of observations required in order for a valid result to be obtained.

ddof: This is optional. Delta Degrees of Freedom is indicated by this argument. N – ddof is the divisor used in calculations, where N is the number of elements.

Return Value:

The covariance of a Series with other Series is returned by the cov() function of the Pandas Series.

Pandas Series cov() Function in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Pass some random list as an argument to the Series() function of the pandas module to create a series.
  • Store it in a variable.
    Pass some random list as an argument to the Series() function of the pandas module to create another series.
  • Store it in another variable.
  • Print the above given first series
  • Print the above given second series
  • Pass the given second series as an argument to the cov() function and apply it on the given first series to get the covariance of the first series with the second and print the result.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random list as an argument to the Series() function
# of the pandas module to create a series.
# Store it in a variable.
gvn_series1 = pd.Series([3, 3.2, 10.1, 5.3, 4, 2, 3, 6])
# Pass some random list as an argument to the Series() function
# of the pandas module to create another series.
# Store it in another variable.
gvn_series2 = pd.Series([3.1, 3, 7.2, 6, 8, 2.5, 3, 1.1])
# Print the above given first series
print("The given first series is:")
print(gvn_series1)
print()
# Print the above given second series
print("The given second series is:")
print(gvn_series2)
print()
# Pass the given second series as an argument to the cov() function and apply it 
# on the given first series to get the covariance of the first series with the second
# and print the result.
print("The covariance of first series with the second:")
print(gvn_series1.cov(gvn_series2))

Output:

The given first series is:
0     3.0
1     3.2
2    10.1
3     5.3
4     4.0
5     2.0
6     3.0
7     6.0
dtype: float64

The given second series is:
0    3.1
1    3.0
2    7.2
3    6.0
4    8.0
5    2.5
6    3.0
7    1.1
dtype: float64

The covariance of first series with the second:
2.989642857142857

Example2

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe.
  • Apply cov() function on the student_rollno and student_marks column of the dataframe to get the covariance of student_rollno column of the dataframe with the student_marks and print the result.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 35, 25, 90]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()
# Apply cov() function on the student_rollno and student_marks column of the 
# dataframe to get the covariance of student_rollno column of the dataframe 
# with the student_marks and print the result.
print("The covariance of student_rollno column of the dataframe with the student_marks:")
print(data_frme['student_rollno'].cov(data_frme['student_marks']))

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2             35
jessy                3             25
sindhu               4             90

The covariance of student_rollno column of the dataframe with the student_marks:
3.333333333333333

 

Python Pandas Timestamp.fromtimestamp() Function

Python Pandas Timestamp.fromtimestamp() Function

What is Timestamp?

A timestamp is a sequence of characters or encoded information that identifies when a particular event occurred, typically providing the date and time of day, and can be accurate to a fraction of a second.

The timestamp method is used for a variety of synchronization purposes, including assigning a sequence order to a multievent transaction so that the transaction can be canceled if a fault occurs. A timestamp can also be used to record time in reference to a specific starting point in time.

Uses of Timestamp:

Timestamps are used to maintain track of information stored online or on a computer. A timestamp indicates when data was generated, shared, modified, or removed.

Here are some examples of how timestamps can be used:

  • A timestamp in a computer file indicates when the file was last modified.
  • Photographs with digital cameras have timestamps that show the date and time of day they were taken.
  • The date and time of the post are included in social media posts.
  • Timestamps are used in online chat and instant messages to record the date and time that a message was delivered, received, or viewed.
  • Timestamps are used in blockchain blocks to confirm the validity of transactions, such as those involving cryptocurrencies.
  • To secure the integrity and quality of data, data management relies on timestamps.
  • Timestamps are used in digital contracts and digital signatures to signify when a document was signed.

Pandas Timestamp.fromtimestamp() Function:

When an integer representing the timestamp value is given to the Timestamp.fromtimestamp() function of the pandas module, it returns a Timestamp object.

Syntax:

Timestamp.fromtimestamp(integer)

Parameters

integer: It is an integer that represents the Timestamp value.

Return Value:

The Timestamp object is is returned by the Timestamp.fromtimestamp() function of the Pandas module.

Pandas Timestamp.fromtimestamp() Function in Python

Example1

Here it returns the new Timestamp object from the given integer value.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random year, month, day, hour, second, tz = ‘Asia/Kolkata’ (Timezone) as the arguments to the Timestamp() function of the pandas module to get the Timestamp object.
  • Store it in a variable.
  • Print the above-obtained Timestamp object
  • Pass some random integer(Timestamp) value as an argument to the fromtimestamp() function and apply it on the above-given Timestamp object to get the new Timestamp object from the given integer value.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
  
# Pass some random year, month, day, hour, second, tz = 'Asia/Kolkata'
# (Timezone) as the arguments to the Timestamp() function of the
# pandas module to get the Timestamp object.
# Store it in a variable.
time_stamp_obj = pd.Timestamp(year = 2019,  month = 5, day = 16, hour = 11, 
                            second = 25, tz = 'Asia/Kolkata')
  
# Print the above obtained Timestamp object
print("The above obtained Timestamp object:", time_stamp_obj)
print()
# Pass some random integer(Timestamp) value as an argument to the fromtimestamp()
# function and apply it on the above given Timestamp object to get the new
# Timestamp object from the given integer value.
print("The Timestamp object from the given integer value:")
time_stamp_obj.fromtimestamp(981324256)

Output:

The above obtained Timestamp object: 2019-05-16 11:00:25+05:30

The Timestamp object from the given integer value:
Timestamp('2001-02-04 22:04:16')

Example2

Approach:

  • Import pandas module using the import keyword.
  • Pass some random year, month, day, hour, second, tz =’US/Eastern’ (Timezone) as the arguments to the Timestamp() function of the pandas module to get the Timestamp object.
  • Store it in a variable.
  • Print the above-obtained Timestamp object
  • Pass some random integer(Timestamp) value as an argument to the fromtimestamp() function and apply it on the above-given Timestamp object to get the new Timestamp object from the given integer value.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
  
# Pass some random year, month, day, hour, second, tz = 'US/Eastern'
# (Timezone) as the arguments to the Timestamp() function of the
# pandas module to get the Timestamp object.
# Store it in a variable.
time_stamp_obj = pd.Timestamp(year = 2003,  month = 10, day = 30, hour = 9, 
                            second = 19, tz = 'US/Eastern')
  
# Print the above obtained Timestamp object
print("The above obtained Timestamp object:", time_stamp_obj)
print()
# Pass some random integer(Timestamp) value as an argument to the fromtimestamp()
# function and apply it on the above given Timestamp object to get the new
# Timestamp object from the given integer value.
print("The Timestamp object from the given integer value:")
time_stamp_obj.fromtimestamp(878621136)

Output:

The above obtained Timestamp object: 2003-10-30 09:00:19-05:00

The Timestamp object from the given integer value:
Timestamp('1997-11-04 05:25:36')

Python Pandas DataFrame ne() Function

Python Pandas DataFrame ne() Function

Pandas DataFrame ne() Function:

The ne() function of the Pandas compares dataframes and other element-by-element for not equal to and returns the outcome of the comparison. It’s the same as dataframe!= other, but with the ability to select the comparison axis (rows or columns) and level.

Syntax:

DataFrame.ne(other, axis='columns', level=None)

Parameters

other: This is required. It indicates any single or multiple element data structure or list-like object

axis: This is optional. Choose between comparing by index (0 or ‘index’) or columns (1 or ‘columns’).

level: This is optional. To broadcast over a level, specify an int or a label that matches the Index values on the passed MultiIndex level. None is the default value.

Return Value:

The result of the comparison i.e, a boolean series is returned.

Pandas DataFrame ne() Function in Python

Example1

Here, the DataFrame is compared to a scalar value using the ne() function.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe
  • Apply ne() function to the dataframe by passing some random number to it and print the result.
  • Here it compares if the entire dataframe has values != 3(not equal to)
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 3, 25, 90]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Apply ne() function to the dataframe by passing some random number
# to it and print the result.
# Here it compares if the entire dataframe has values != 3
print("Checking if the entire dataframe has values != 3:")
print(data_frme.ne(3))

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2              3
jessy                3             25
sindhu               4             90

Checking if the entire dataframe has values != 3:
        student_rollno  student_marks
virat             True           True
nick              True          False
jessy            False           True
sindhu            True           True

Example2

Here, the ‘other’ argument can be provided as a list to compare different columns with different scalar values

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe.
  • Apply ne() function on the dataframe by passing list as an argument to it which compares the corresponding list elements with the dataframe and print the result.
  • Here it checks if the elements of the student_rollno column of the dataframe!=3 and student_marks column of the dataframe!=40.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 40, 25, 40]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Apply ne() function on the dataframe by passing list as an argument to it 
# which compares the corresponding list elements with the dataframe and print the result.
# Here it checks if the elements of the student_rollno column of the dataframe!=3
# and student_marks column of the dataframe!=40.
print("Checking if the student_rollno column!=3 and student_marks column!=40:")
print(data_frme.ne([3, 40]))

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2             40
jessy                3             25
sindhu               4             40

Checking if the student_rollno column!=3 and student_marks column!=40:
        student_rollno  student_marks
virat             True           True
nick              True          False
jessy            False           True
sindhu            True          False

Example3

Here, ne() function is used on specific columns rather than the entire DataFrame.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe.
  • Apply ne() function on the specified column of dataframe by passing some random number to it and print the result.
  • Here it compares if the elements of student_rollno column!=3
  • Apply ne() function on the specified columns of the dataframe by passing list as an argument to it which compares the corresponding list elements with the specified columns of the dataframe and print the result.
  • Here it compares if the elements of the student_rollno column of the dataframe!=3 and student_marks column of the dataframe!=40.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 40, 25, 40]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()
# Apply ne() function on the specified column of dataframe 
# by passing some random number to it and print the result.
# Here it compares if the elements of student_rollno column!=3
print("Checking if the student_rollno column has values !=3")
print(data_frme["student_rollno"].ne(3))
print()
# Apply ne() function on the specified columns of the dataframe by passing list
# as an argument to it which compares the corresponding list elements with
# the specified columns of the dataframe and print the result.
# Here it compares if the elements of the student_rollno column of the dataframe!=3
# and student_marks column of the dataframe!=40.
print("Checking if the student_rollno column!=3 and student_marks column!=40:")
print(data_frme[["student_rollno", "student_marks"]].ne([3, 40]))

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2             40
jessy                3             25
sindhu               4             40

Checking if the student_rollno column has values !=3
virat      True
nick       True
jessy     False
sindhu     True
Name: student_rollno, dtype: bool

Checking if the student_rollno column!=3 and student_marks column!=40:
        student_rollno  student_marks
virat             True           True
nick              True          False
jessy            False           True
sindhu            True          False

Example4

In a DataFrame, the ne() method can be used to compare two series/column element-by-element for NOT equal to condition.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary) as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe.
  • Compare both the columns gvn_list1 and gvn_list2 using the ne() function and store the result as a new column in the dataframe.
  • Here it checks if gvn_list1 != gvn_list2 element-wise.
  • Print the dataframe after adding a new column(gvn_list1 != gvn_list2).
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary) as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme  = pd.DataFrame({
  "gvn_list1": [45, 7, 54, 90],
  "gvn_list2": [55, 7, 54, 44]
})
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Compare both the columns gvn_list1 and gvn_list2 using the ne() function
# and store the result as a new column in the dataframe.
# Here it checks if gvn_list1 != gvn_list2 element-wise.
data_frme ['gvn_list1 != gvn_list2'] = data_frme ['gvn_list1'].ne(data_frme ['gvn_list2'])
# Print the dataframe after adding a new column(gvn_list1 != gvn_list2)
print("The dataframe after adding a new column(gvn_list1 != gvn_list2):")
print(data_frme )

Output:

The given Dataframe:
   gvn_list1  gvn_list2
0         45         55
1          7          7
2         54         54
3         90         44

The dataframe after adding a new column(gvn_list1 != gvn_list2):
   gvn_list1  gvn_list2  gvn_list1 != gvn_list2
0         45         55                    True
1          7          7                   False
2         54         54                   False
3         90         44                    True

 

Python Pandas DataFrame ge() Function

Python Pandas DataFrame ge() Function

Pandas DataFrame ge() Function:

The ge() method of the Pandas module compares dataframe and other element-by-element for greater than equal to and returns the outcome of the comparison. It’s similar to dataframe >= other, but with the ability to select the comparison axis (rows or columns) and level.

Syntax:

DataFrame.ge(other, axis='columns', level=None)

Parameters

other: This is required. It indicates any single or multiple element data structure or list-like object

axis: This is optional. Choose between comparing by index (0 or ‘index’) or columns (1 or ‘columns’).

level: This is optional. To broadcast over a level, specify an int or a label that matches the Index values on the passed MultiIndex level. None is the default value.

Return Value:

The result of the comparison i.e, a boolean series is returned.

Pandas DataFrame ge() Function in Python

Example1

Here, the DataFrame is compared to a scalar value using the ge() function.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe
  • Apply ge() function to the dataframe by passing some random number to it and print the result.
  • Here it compares if the entire dataframe has values >= 3
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 35, 25, 90]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Apply ge() function to the dataframe by passing some random number
# to it and print the result.
# Here it compares if the entire dataframe has values >= 3
print("Checking if the entire dataframe has values >= 3:")
print(data_frme.ge(3))

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2             35
jessy                3             25
sindhu               4             90

Checking if the entire dataframe has values >= 3:
        student_rollno  student_marks
virat            False           True
nick             False           True
jessy             True           True
sindhu            True           True

Example2

Here, the ‘other’ argument can be provided as a list to compare different columns with different scalar values

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe
  • Apply ge() function on the dataframe by passing list as an argument to it which compares the corresponding list elements with the dataframe and print the result.
  • Here it checks if the elements of the student_rollno column of the dataframe>=3 and student_marks column of the dataframe>=40.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 40, 25, 90]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Apply ge() function on the dataframe by passing list as an argument to it 
# which compares the corresponding list elements with the dataframe and print the result.
# Here it checks if the elements of the student_rollno column of the dataframe>=3.
# and student_marks column of the dataframe>=40.
print("Checking if the student_rollno column>=3 and student_marks column>=40:")
print(data_frme.ge([3, 40]))

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2             40
jessy                3             25
sindhu               4             90

Checking if the student_rollno column>=3 and student_marks column>=40:
        student_rollno  student_marks
virat            False           True
nick             False           True
jessy             True          False
sindhu            True           True

Example3

Here, ge() function is used on specific columns rather than the entire DataFrame.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe.
  • Apply ge() function on the specified column of dataframe by passing some random number to it and print the result.
  • Here it compares if the elements of student_rollno column>=3
  • Apply ge() function on the specified columns of the dataframe by passing list as an argument to it which compares the corresponding list elements with the specified columns of the dataframe and print the result.
  • Here it compares if the elements of the student_rollno column of the dataframe>=3 and student_marks column of the dataframe>=40.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 40, 25, 90]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()
# Apply ge() function on the specified column of dataframe 
# by passing some random number to it and print the result.
# Here it compares if the elements of student_rollno column>=3
print("Checking if the student_rollno column>=3")
print(data_frme["student_rollno"].ge(3))
print()
# Apply ge() function on the specified columns of the dataframe by passing list
# as an argument to it which compares the corresponding list elements with
# the specified columns of the dataframe and print the result.
# Here it compares if the elements of the student_rollno column of the dataframe>=3.
# and student_marks column of the dataframe>=40.
print("Checking if the student_rollno column>=3 and student_marks column>=40:")
print(data_frme[["student_rollno", "student_marks"]].ge([3, 40]))

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2             40
jessy                3             25
sindhu               4             90

Checking if the student_rollno column>=3
virat     False
nick      False
jessy      True
sindhu     True
Name: student_rollno, dtype: bool

Checking if the student_rollno column>=3 and student_marks column>=40:
        student_rollno  student_marks
virat            False           True
nick             False           True
jessy             True          False
sindhu            True           True

Example4

In a DataFrame, the ge() method can be used to compare two series/column element-by-element for greater than equal to condition.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary) as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe.
  • Compare both the columns gvn_list1 and gvn_list2 using the ge() function and store the result as a new column in the dataframe.
  • Here it checks if gvn_list1 >= gvn_list2 element-wise.
  • Print the dataframe after adding a new column(gvn_list1 >= gvn_list2).
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary) as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme  = pd.DataFrame({
  "gvn_list1": [45, 24, 54, 90],
  "gvn_list2": [55, 7, 54, 44]
})
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Compare both the columns gvn_list1 and gvn_list2 using the ge() function
# and store the result as a new column in the dataframe.
# Here it checks if gvn_list1 >= gvn_list2 element-wise.
data_frme ['gvn_list1 >= gvn_list2'] = data_frme ['gvn_list1'].ge(data_frme ['gvn_list2'])
# Print the dataframe after adding a new column(gvn_list1 >= gvn_list2)
print("The dataframe after adding a new column(gvn_list1 >= gvn_list2):")
print(data_frme )

Output:

The given Dataframe:
   gvn_list1  gvn_list2
0         45         55
1         24          7
2         54         54
3         90         44

The dataframe after adding a new column(gvn_list1 >= gvn_list2):
   gvn_list1  gvn_list2  gvn_list1 >= gvn_list2
0         45         55                   False
1         24          7                    True
2         54         54                    True
3         90         44                    True

 

Python Pandas DataFrame mul() Function

Python Pandas DataFrame mul() Function

Python is an excellent language for data analysis, due to a strong ecosystem of data-centric Python tools. One of these packages is Pandas, which makes importing and analyzing data a lot easier.

Pandas DataFrame mul() Function:

The mul() method of the Pandas module returns element-by-element multiplication of dataframe and other. It’s the same as dataframe * other, but with the ability to provide a fill_value as one of the parameters to replace missing data.

Syntax:

DataFrame.mul(other, axis='columns', level=None, fill_value=None)

Parameters

other: This is required. It indicates any single or multiple element data structure or list-like object. The type of this may be scalar, sequence, Series, or DataFrame

axis: This is optional. It indicates whether to compare by index (0 or ‘index’) and columns (1 or ‘columns’). axis to match Series index on, for Series input. The default value is ‘columns.’

level: This is optional. To broadcast over a level, specify an int or a label that matches the Index values on the passed MultiIndex level. None is the default value. The type of this may be int or label.

fill_value: This is optional. It indicates a value to fill in any current missing (NaN) values, as well as any new elements required for DataFrame alignment to succeed. The result will be missing if data in both corresponding DataFrame locations is missing. The type of this may be float or None. None is the default value.

Return Value:

The result of the arithmetic operation is returned.

Pandas DataFrame mul() Function in Python

Example1

Here, to multiply a scalar value to the entire DataFrame, we used the mul() function.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe
  • Store it in a variable.
  • Print the given dataframe
  • Apply mul() function to the dataframe by passing some random number to it and print the result.
  • Here it multiplies 5 with the entire dataframe.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 35, 25, 90]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Apply mul() function to the dataframe by passing some random number
# to it and print the result.
# Here it multiplies 5 with the entire dataframe.
print("The result dataframe after multiplying 5 with the entire dataframe:")
print(data_frme.mul(5))

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2             35
jessy                3             25
sindhu               4             90

The result dataframe after multiplying 5 with the entire dataframe:
        student_rollno  student_marks
virat                5            400
nick                10            175
jessy               15            125
sindhu              20            450

Example2

Here, the ‘other’ argument can be provided as a list to multiply different scalar values with different columns.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe
  • Store it in a variable.
  • Print the given dataframe.
  • Apply mul() function to the dataframe by passing list as argument to it which multiplies corresponding list elements with the dataframe and print the result.
  • Here it multiplies 2 with the student_rollno column of the dataframe and 10 with the student_marks column of the dataframe.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 35, 25, 90]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Apply mul() function to the dataframe by passing list as argument to it 
# which multiplies corresponding list elements with the dataframe and print the result.
# Here it multiplies 2 with the student_rollno column of the dataframe.
# and 10 with the student_marks column of the dataframe.
print("The dataframe after multiplying 2 with student_rollno, 10 with student_marks columns:")
print(data_frme.mul([2, 10]))

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2             35
jessy                3             25
sindhu               4             90

The dataframe after multiplying 2 with student_rollno, 10 with student_marks columns:
        student_rollno  student_marks
virat                2            800
nick                 4            350
jessy                6            250
sindhu               8            900

Example3

Here, mul() function is used on specific columns rather than the entire DataFrame.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe
  • Store it in a variable.
  • Print the given dataframe
  • Apply mul() function to the specified column of dataframe by passing some random number to it and print the result.
  • Here it multiplies 5 with the student_rollno column of the dataframe.
  • Apply mul() function to the specified columns of dataframe which multiplies corresponding list elements with the dataframe columns and print the result.
  • Here it multiplies 2 with the student_rollno column of the dataframe and 10 with the student_marks column of the dataframe.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 35, 25, 90]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Apply mul() function to the specified column of dataframe by passing some random number
# to it and print the result.
# Here it multiplies 5 with the student_rollno column of the dataframe.
print("The dataframe after multiplying 5 with the student_rollno column:")
print(data_frme["student_rollno"].mul(5))
print()

# Apply mul() function to the specified columns of dataframe which multiplies corresponding 
# list elements with the dataframe columns and print the result.
# Here it multiplies 2 with the student_rollno column of the dataframe
# and 10 with the student_marks column of the dataframe.
print("The dataframe after multiplying 2 with student_rollno, 10 with student_marks columns:")
print(data_frme[["student_rollno", "student_marks"]].mul([2, 10]))

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2             35
jessy                3             25
sindhu               4             90

The dataframe after multiplying 5 with the student_rollno column:
virat      5
nick      10
jessy     15
sindhu    20
Name: student_rollno, dtype: int64

The dataframe after multiplying 2 with student_rollno, 10 with student_marks columns:
        student_rollno  student_marks
virat                2            800
nick                 4            350
jessy                6            250
sindhu               8            900

Example4

In a DataFrame, the mul() method can be used to obtain the element-wise multiplication of two series/columns.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe
  • Store it in a variable.
  • Print the given dataframe.
  • Multiply the columns student_rollno and student_marks using the mul() function and store it as a new column in the dataframe.
  • Print the dataframe after adding a new column(student_rollno * student_marks).
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "student_rollno": [1, 2, 3, 4],
  "student_marks": [80, 35, 25, 90]},
  index= ["virat", "nick" , "jessy", "sindhu"]
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Multiply the columns student_rollno and student_marks using the mul() 
# function and store it in as a new column in the dataframe.
data_frme['student_rollno * student_marks'] = data_frme['student_rollno'].mul(data_frme['student_marks'])
# Print the dataframe after adding a new column(student_rollno * student_marks)
print("The DataFrame after adding a new column(student_rollno * student_marks):")
print(data_frme)

Output:

The given Dataframe:
        student_rollno  student_marks
virat                1             80
nick                 2             35
jessy                3             25
sindhu               4             90

The DataFrame after adding a new column(student_rollno * student_marks):
        student_rollno  student_marks  student_rollno * student_marks
virat                1             80                              80
nick                 2             35                              70
jessy                3             25                              75
sindhu               4             90                             360