Python shift – Python Pandas Series shift() Function

Python Pandas Series shift() Function

Pandas Series shift() Function:

Python shift: The shift() function of the Pandas Series shifts the index by the given number of periods, with an optional time freq.

When no frequency is specified, the function shifts the index without realigning the data. If freq is specified (the index must be date or datetime else a NotImplementedError will be raised), the index will be incremented using the periods and the freq.

Syntax:

Series.shift(periods=1, freq=None, axis=0, fill_value)

Parameters

periods: This is optional. It represents the number of periods to shift. It can be both positive and negative. 1 is the default.

freq: This is optional. It indicates freqDateOffset, tseries.offsets, timedelta, or str. It is the offset to use from the tseries module or time rule (for example, ‘EOM’). The index values are shifted but the data is not realigned if freq is given. None is the default.

axis: This is optional. It indicates 0 or ‘index’, 1 or ‘columns’. If the value is 0 or ‘index,’ the shift is in the column direction. If 1 or ‘columns’ is specified, the shift occurs in the row direction. 0 is the default.

fill_value: This is optional. It is the scalar value that will be used for newly added missing values. The default value is self.dtype.na_value.

Return Value:

The shifted input object is returned by the shift() function of the Pandas Series.

Pandas Series shift() Function in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list(start, end dates) as arguments to the DataFrame() function of the pandas module to create a dataframe
  • Store it in a variable.
  • Print the given dataframe
  • Apply shift() function the given dataframe to shift the dataframe by 1 period column-wise and print the result
  • Apply shift() function the given dataframe by passing some random number k as an argument to shift the dataframe by k periods column-wise and print the result.
  • Apply shift() function the given dataframe by passing axis=1 as an argument to shift the dataframe by 1 period row-wise 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(start, end dates)
# as arguments to the DataFrame() function of the pandas module 
# to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "first_column": [10, 15, 25, 35, 45],
  "second_column": [1, 2, 3, 4, 5],
  "third_column": [3, 5, 7, 9, 11]},
  index=pd.date_range("2019-06-01", "2019-06-05")
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()
# Apply shift() function the given dataframe to shift the dataframe
# by 1 period column-wise and print the result
print("Shifting the dataframe by 1 period column-wise:")
print(data_frme.shift())
print()
# Apply shift() function the given dataframe by passing some random number k 
# as an argument to shift the dataframe by k periods column-wise and print the result.
print("Shifting the dataframe by 2 periods column-wise:")
print(data_frme.shift(2))
print()
# Apply shift() function the given dataframe by passing axis=1 as  
# an argument to shift the dataframe by 1 period row-wise and print the result.
print("Shifting the given dataframe by 1 period row-wise:")
print(data_frme.shift(axis=1))

Output:

The given Dataframe:
            first_column  second_column  third_column
2019-06-01            10              1             3
2019-06-02            15              2             5
2019-06-03            25              3             7
2019-06-04            35              4             9
2019-06-05            45              5            11

Shifting the dataframe by 1 period column-wise:
            first_column  second_column  third_column
2019-06-01           NaN            NaN           NaN
2019-06-02          10.0            1.0           3.0
2019-06-03          15.0            2.0           5.0
2019-06-04          25.0            3.0           7.0
2019-06-05          35.0            4.0           9.0

Shifting the dataframe by 2 periods column-wise:
            first_column  second_column  third_column
2019-06-01           NaN            NaN           NaN
2019-06-02           NaN            NaN           NaN
2019-06-03          10.0            1.0           3.0
2019-06-04          15.0            2.0           5.0
2019-06-05          25.0            3.0           7.0

Shifting the given dataframe by 1 period row-wise:
            first_column  second_column  third_column
2019-06-01           NaN             10             1
2019-06-02           NaN             15             2
2019-06-03           NaN             25             3
2019-06-04           NaN             35             4
2019-06-05           NaN             45             5

Example2

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list(start, end dates) as arguments to the DataFrame() function of the pandas module to create a dataframe
  • Store it in a variable.
  • Print the given dataframe.
  • Apply shift() function the given dataframe by passing some random number k as an argument to shift the dataframe by k periods column-wise and print the result.
  • Apply shift() function the given dataframe by passing some random number k, fill_value as the arguments to shift the dataframe by k periods column-wise with the given fill_value 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(start, end dates)
# as arguments to the DataFrame() function of the pandas module 
# to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "first_column": [10, 15, 25, 35, 45],
  "second_column": [1, 2, 3, 4, 5],
  "third_column": [3, 5, 7, 9, 11]},
  index=pd.date_range("2019-06-01", "2019-06-05")
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Apply shift() function the given dataframe by passing some random number k 
# as an argument to shift the dataframe by k periods column-wise and print the result.
print("Shifting the dataframe by 2 periods column-wise:")
print(data_frme.shift(2))
print()

# Apply shift() function the given dataframe by passing some random number k, fill_value 
# as the arguments to shift the dataframe by k periods column-wise with the given fill_value 
# and print the result.
print("Shifting the dataframe by 2 periods column-wise with fill_value=100:")
print(data_frme.shift(2, fill_value=100))

Output:

The given Dataframe:
            first_column  second_column  third_column
2019-06-01            10              1             3
2019-06-02            15              2             5
2019-06-03            25              3             7
2019-06-04            35              4             9
2019-06-05            45              5            11

Shifting the dataframe by 2 periods column-wise:
            first_column  second_column  third_column
2019-06-01           NaN            NaN           NaN
2019-06-02           NaN            NaN           NaN
2019-06-03          10.0            1.0           3.0
2019-06-04          15.0            2.0           5.0
2019-06-05          25.0            3.0           7.0

Shifting the dataframe by 2 periods column-wise with fill_value=100:
            first_column  second_column  third_column
2019-06-01           100            100           100
2019-06-02           100            100           100
2019-06-03            10              1             3
2019-06-04            15              2             5
2019-06-05            25              3             7

Example3

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary), index list(start, end dates) as arguments to the DataFrame() function of the pandas module to create a dataframe
  • Store it in a variable.
  • Print the given dataframe.
  • Apply shift() function the given dataframe by passing periods as some random number k, freq=’D’ as the arguments to shift the index by k periods with frequency D(date) and print the result.
  • Apply shift() function the given dataframe by passing periods as some random number k, freq=’infer’ as the arguments to shift the index by k periods with frequency infer 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(start, end dates)
# as arguments to the DataFrame() function of the pandas module 
# to create a dataframe
# Store it in a variable.
data_frme = pd.DataFrame({
  "first_column": [10, 15, 25, 35, 45],
  "second_column": [1, 2, 3, 4, 5],
  "third_column": [3, 5, 7, 9, 11]},
  index=pd.date_range("2019-06-01", "2019-06-05")
)
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Apply shift() function the given dataframe by passing periods as some random number k,
# freq='D' as the arguments to shift the index by k periods with frequency D(date)
# and print the result.
print("Shifting the index by 2 periods with freq=D:")
print(data_frme.shift(periods=2, freq='D'))
# Apply shift() function the given dataframe by passing periods as some random number k,
# freq='infer' as the arguments to shift the index by k periods with frequency infer
# and print the result.
print("Shifting the index by 2 periods with freq=infer:")
print(data_frme.shift(periods=2, freq='infer'))

Output:

The given Dataframe:
            first_column  second_column  third_column
2019-06-01            10              1             3
2019-06-02            15              2             5
2019-06-03            25              3             7
2019-06-04            35              4             9
2019-06-05            45              5            11

Shifting the index by 2 periods with freq=D:
            first_column  second_column  third_column
2019-06-03            10              1             3
2019-06-04            15              2             5
2019-06-05            25              3             7
2019-06-06            35              4             9
2019-06-07            45              5            11
Shifting the index by 2 periods with freq=infer:
            first_column  second_column  third_column
2019-06-03            10              1             3
2019-06-04            15              2             5
2019-06-05            25              3             7
2019-06-06            35              4             9
2019-06-07            45              5            11

 

Drop_duplicates python – Python Pandas Series drop_duplicates() Function

Python Pandas Series drop_duplicates() Function

Pandas Series drop_duplicates() Function:

Drop_duplicates python: The drop_duplicates() function of the Pandas Series returns a Series with duplicate values deleted.

Syntax:

Series.drop_duplicates(keep='first',  inplace=False)

Parameters

keep:  This is optional. It specifies which duplicates(if present) to keep. Possible values include:

  • first- This is the Default. Except for the first occurrence, remove all duplicates.
  • last – Except for the last occurrence, remove all duplicates.
  • False – Remove all duplicates.

inplace: This is optional. If set to True, it does the operation in place and returns None.

Return Value:

Drop_duplicates(): A Series with duplicates removed or None if inplace=True is returned by the drop_duplicates() function of the Pandas Series.

Pandas Series drop_duplicates() Function in Python

Example1

Here, the drop_duplicates() function removes the duplicate values from a Series given.

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 drop_duplicates() function on the given series to remove all the duplicate(repeated)elements present in the given series 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_series = pd.Series([1, 3, 1, 5, 4, 3, 2])
# Print the above given series
print("The given series is:")
print(gvn_series)
print()
# Apply drop_duplicates() function on the given series to remove 
# all the duplicate(repeated)elements present in the given series 
# and print the result.
print("The given series after removing all the duplicates:")
print(gvn_series.drop_duplicates())

Output:

The given series is:
0    1
1    3
2    1
3    5
4    4
5    3
6    2
dtype: int64

The given series after removing all the duplicates:
0    1
1    3
3    5
4    4
6    2
dtype: int64

Example2

Here, we can indicate which duplicate value to keep by using the keep argument.

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 drop_duplicates() function on the given series by passing keep=’first’ as an argument to it to remove all the duplicate elements present in the given series except the first occurrence and print the result.
  • Apply drop_duplicates() function on the given series by passing keep=’last’ as an argument to it to remove all the duplicate elements present in the given series except the last occurrence 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_series = pd.Series([1, 3, 1, 5, 4, 3, 2])
# Print the above given series
print("The given series is:")
print(gvn_series)
print()
# Apply drop_duplicates() function on the given series by passing keep='first'
# as an argument to it to remove all the duplicate elements present in the given series 
# except the first occurrence and print the result.
print("The given series after removing all the duplicates except the first occurrence:")
print(gvn_series.drop_duplicates(keep='first'))
print()
# Apply drop_duplicates() function on the given series by passing keep='last'
# as an argument to it to remove all the duplicate elements present in the given series 
# except the last occurrence and print the result.
print("The given series after removing all the duplicates except the last occurrence:")
print(gvn_series.drop_duplicates(keep='last'))

Output:

The given series is:
0    1
1    3
2    1
3    5
4    4
5    3
6    2
dtype: int64

The given series after removing all the duplicates except the first occurrence:
0    1
1    3
3    5
4    4
6    2
dtype: int64

The given series after removing all the duplicates except the last occurrence:
2    1
3    5
4    4
5    3
6    2
dtype: int64

 

Basics of Python – Operators and Operands

Python operands: In this Page, We are Providing Basics of Python – Operators and Operands. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – Operators and Operands

Operators and operands

Operands in python: An operator is a symbol (such as +, x, etc.) that represents an operation. An operation is an action or •procedure that produces a new value from one or more input values called operands. There are two types of operators: unary and binary. The unary operator operates only on one operand, such as negation. On the other hand, the binary operator operates on two operands, which include addition, subtraction, multiplication, division, exponentiation operators, etc. Consider an expression 3 + 8, here 3 and 8 are called operands, while V is called operator. The operators can also be categorized into:

  • Arithmetic operators.
  • Comparison (or Relational) operators.
  • Assignment operators.
  • Logical operators.
  • Bitwise operators.
  • Membership operators.
  • Identity operators.

Arithematics operators

Python unary operators: Table 2-2 enlists the arithmetic operators with a short note on the operators.

Operator

Description

+

Addition operator- Add operands on either side of the operator.

Subtraction operator – Subtract the right-hand operand from the left-hand operand.

*

Multiplication operator – Multiply operands on either side of the operator.

/

Division operator – Divide left-hand operand by right-hand operand.

%

Modulus operator – Divide left-hand operand by right-hand operand and return the remainder.

**

Exponent operator – Perform exponential (power) calculation on operands.

//

Floor Division operator – The division of operands where the result is the quotient in which the digits after the decimal point are removed.

The following example illustrates the use of the above-discussed operators.

>>> a=20 
>>> b=45.0
>>> a+b
65.0
>>> a-b
-25.0
>>> a*b
900.0 
>>> b/a 
2.25 
>>> b%a
5.0
>>> a**b
3.5184372088832e+58 
>>> b//a
2.0

Relational operators

A relational operator is an operator that tests some kind of relation between two operands. Tables 2-3 enlist the relational operators with descriptions.

Operator

Description

==

Check if the values of the two operands are equal.

!=

Check if the values of the two operands are not equal.

<>

Check if the value of two operands is not equal (same as != operator).

>

Check if the value of the left operand is greater than the value of the right operand.

<

Check if the value of the left operand is less than the value of the right operand.

>=

Check if the value of the left operand is greater than or equal to the value of the right operand.

<=

Check if the value of the left operand is less than or equal to the value of the right operand.

The following example illustrates the use of the above-discussed operators.

>>> a,b=20,40
>>> a==b
False 
>>> a!=b 
True
>>> a<>b 
True 
>>> a>b 
False 
>>> a<b 
True
>>> a>=b 
False 
>>> a<=b 
True

Assignment operators

The assignment operator is an operator which is used to bind or rebind names to values. The augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement. An augmented assignment expression like x+=l can be rewritten as x=x+l. Tables 2-4 enlist the assignment operators with descriptions.

Operator

Description

=

Assignment operator- Assigns values from right side operand to left side operand.

+=

Augmented assignment operator- It adds the right-side operand to the left side operand and assigns the result to the left side operand.

-=

Augmented assignment operator- It subtracts the right-side operand from the left side operand and assigns the result to the left side operand.

*=

Augmented assignment operator- It multiplies the right-side operand with the left side operand and assigns the result to the left side operand.

/=

Augmented assignment operator- It divides the left side operand with the right side operand and assigns the result to the left side operand.

%=

Augmented assignment operator- It takes modulus using two operands and assigns the result to left side operand.

* *=

Augmented assignment operator- Performs exponential (power) calculation on operands and assigns value to the left side operand.

//=

Augmented assignment operator- Performs floor division on operators and assigns value to the left side operand.

The following example illustrates the use of the above-discussed operators.

>>> a,b=20,40 
>>> c=a+b 
>>> c 
60
>>> a,b=2.0,4.5 
>>>c=a+b
>>> C
6.5
>>> c+=a 
>>> c
8.5
>>> c-=a 
>>> c
6.5
>>> c*=a 
>>> c
13.0
>>> c/=a 
>>> c 
6.5
>>> c%=a 
>>> c 
0.5
>>> c**=a 
>>> c 
0.25
>>> c//=a 
>>> c 
0.0

Bitwise operators

A bitwise operator operates on one or more bit patterns or binary numerals at the level of their individual bits. Tables 2-5 enlist the bitwise operators with descriptions.

Operator

Description

&

Binary AND operator- Copies corresponding binary 1 to the result, if it exists in both operands.

|

Binary OR operator- Copies corresponding binary 1 to the result, if it exists in either operand.

Binary XOR operator- Copies corresponding binary 1 to the result, if it is set in one operand, but not both.

~

Binary ones complement operator- It is unary and has the effect of flipping bits.

<<

Binary left shift operator- The left side operand bits are moved to the left side by the number on the right-side operand.

>>

Binary right shift operator- The left side operand bits are moved to the right side by the number on the right-side operand.

The following example illustrates the use of the above-discussed operators.

>>> a,b=60,13 
>>> a&b 
12
>>> a | b
61 
>>> a∧b
49 
>>> ~a
-61 
>>> a< < 2
240 
>>> a>>2
15

In the above example, the binary representation of variables a and b are 00111100 and 00001101, respectively. The above binary operations example is tabulated in Tables 2-6.

Bitwise operation

Binary representation Decimal representation

a&b

00001100

12

a | b

00111101

61

ab

00110001

49

~a

11000011 -61
a<<2 11110000

240

a>>2 00001111

15

Logical operators

Logical operators compare boolean expressions and return a boolean result. Tables 2-6 enlist the logical operators with descriptions.

Operator

Description

and

Logical AND operator- If both the operands are true (or non-zero), then the condition becomes true.

or

Logical OR’operator- If any of the two operands is true (or non-zero), then the condition becomes true.

not

Logical NOT operator- The result is reverse of the logical state of its operand. If the operand is true (or non-zero), then the condition becomes false.

The following example illustrates the use of the above-discussed operators.

>>> 5>2 and 4<8 
True
>>> 5>2 or 4>8 
True
>>> not (5>2)
False

Membership operators

A membership operator is an operator which tests for membership in a sequence, such as string, list, tuple, etc. Table 2-7 enlists the membership operators.

Operator

Description

In

Evaluate to true, if it finds a variable in the specified sequence; otherwise false.

not in

Evaluate to true, if it does not find a variable in the specified sequence; otherwise false.
>>> 5 in [0, 5, 10, 15]
True 
>>> 6 in [0, 5, 10, 15]
False
>>> 5 not in [0, 5, 10, 15]
False 
>>> 6 not in [0, 5, 10, 15]
True

Identity operators

Identity operators compare the memory locations of two objects. Table 2-8 provides a list of identity operators including a small explanation.

Operator

Description

is

Evaluates to true, if the operands on either side of the operator point to the same object, and false otherwise.

is not

Evaluates to false, if the operands on either side of the operator point to the same object, and true otherwise.

The following example illustrates the use of the above-discussed operators.

>>> a=b=3.1
>>> a is b 
True 
>>> id (a)
3 0 9 8 4 5 2 8 
>>> id (b)
30984528 
>>> c,d=3.1,3.1 
>>> c is d 
False 
>>> id (c)
35058472 
>>> id (d)
30984592
>>> c is not d
True 
>>> a is not b
False

Operator precedence

Operator precedence determines how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. In the expression x=7+3*2, x is assigned 13, not 20, because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7.

Table 2-10 summarizes the operator’s precedence in Python, from lowest precedence to highest precedence (from top to bottom). Operators in the same box have the same precedence.

Operator
not, or, and
in, not in
is, is not
=, %, =/, =//, -=, +=, *=, **=
<>, ==, !=
<=, <, >, >=
∧, |
&
>>,<<
+, –
*, /, %, //
∼,+,-
**

Python tuple to array – Create NumPy Array from List, Tuple or List of Lists in Python

Methods to create NumPy array from list, tuple, or list of lists in Python

Python tuple to array: In this article, we will discuss some basics of NumPy array and how to create NumPy array from lists, tuples, and Lists of lists in python.

NumPy

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it in our program and then we can easily use the functionality of NumPy in our program.

numpy.array()

This method is going to be widely used in our program so it will be beneficial to study this method in advance so that it will be easy for us to understand the concepts. This method helps us to create a numpy array from already defined data structures in python like lists, tuples, and nested lists.

Syntax: numpy.array(object, dtype=None, copy=True, order=‘K’, subok=False, ndmin=0)

This method returns a numpy array.

numpy.asarray()

This method helps us to create a numpy array from already defined data structures in python like lists, tuples, and nested lists.

Syntax: numpy.asarray(arr, dtype=None, order=None)

Difference between numpy.array() and numpy.asarray()

The major difference between both the methods is that numpy.array() will make a duplicate of original copy while the numpy.asarray() make changes in the original copy.

Create a numpy array from a list

  • Method 1-Using numpy.array()

In this method, we will see how we can create a numpy array from the list in python. When we look at the parameter of this method we see that in the parameter one parameter is an object that clearly gives us a hint that we can pass our list in this method and we may get our output in the form of NumPy array. Let us see this method with the help of an example.

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

Output

[1 2 3 4 5 6]
<class 'numpy.ndarray'>

Here we see how we easily create our numpy array from the list using numpy.array() method.

  • Method 2-Using numpy.asarray()

This method also works in the same way as numpy.array() work.We just simply pass our list object in the function and we will get our numpy array. Let see this with an example.

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

Output

[1 2 3 4 5 6]
<class 'numpy.ndarray'>

Create a numpy array from a tuple

  • Method 1-Using numpy.array()

Here the procedure is the same as we discuss in the case of lists. Here instead of a list, we have to pass out a tuple and we get our numpy array. Let see this with the help of an example.

t=(1,2,3,4,5,6)
array=np.array(t)
print(array)
print(type(array))

Output

[1 2 3 4 5 6]
<class 'numpy.ndarray'>
  • Method 2-Using numpy.asarray()

Just like we use this method in the case of lists here we also use this in a similar way. But here instead of using the list, we pass tuple as an object. Let see this with the help of an example.

t=(1,2,3,4,5,6)
array=np.asarray(t)
print(array)
print(type(array))

Output

[1 2 3 4 5 6]
<class 'numpy.ndarray'>

Create a 2d Numpy array from a list of list

numpy. array() method will also work here and the best part is that the procedure is the same as we did in the case of a single list.In this case, we have to pass our list of lists as an object and we get our output as a 2d array.Let see this with the help of an example.

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

Output

[[1 2 3]
 [4 5 6]]
<class 'numpy.ndarray'>

So these are the methods to create numpy array from list,tuples and lists of lists.

Check if number is prime python – Python Program to Check a Number is Prime or Not

Program to Check Prime Number

Check if number is prime 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

Factors of a number:

Check if a number is prime python: When two whole numbers are multiplied, the result is a product. The factors of the product are the numbers we multiply.

In mathematics, a factor is a number or algebraic expression that equally divides another number or expression, leaving no remainder.

Prime Number:

Python check if number is prime: A prime number is a positive integer greater than 1 that has no other variables except 1 and the number itself. Since they have no other variables, the numbers 2, 3, 5, 7, and so on are prime numbers.

Given a number, the task is to check whether the given number is prime or not.

Examples:

Example 1:

Input:

number =5

Output:

The given number 5 is prime number

Example 2:

Input:

number =8

Output:

The given number 8 is not prime number

Example 3:

Input:

number =2

Output:

The given number 2 is not prime number

Program to Check Prime Number in Python Programming

How to check if a number is prime in python: Below are the ways to check whether the given number is prime or not:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Using for loop to loop from 2 to N-1 using flag or temp variable

Python check if prime: To see if there are any positive divisors other than 1 and number itself, we divide the input number by all the numbers in the range of 2 to (N – 1).

If a divisor is found, the message “number is not a prime number” is displayed otherwise, the message “number is a prime number” is displayed.

We iterate from 2 to N-1 using for loop.

Below is the implementation:

# given number
number = 5
# intializing a temporary variable with False
temp = False
# We will check if the number is greater than 1 or not
# since prime numbers starts from 2
if number > 1:
    # checking the divisors of the number
    for i in range(2, number):
        if (number % i) == 0:
            # if any divisor is found then set temp to true since it is not prime number
            temp = True
            # Break the loop if it is not prime
            break
if(temp):
    print("The given number", number, "is not prime number")
else:
    print("The given number", number, "is prime number")

Output:

The given number 5 is prime number

Explanation:

Is prime python: We checked whether a number is prime or not in this program . Prime numbers are not  those that are smaller than or equal to one. As a result, we only go forward if the number is greater than one.

We check whether a number is divisible exactly by any number between 2 and number – 1. We set temp to True and break the loop if we find a factor in that range, indicating that the number is not prime.

We check whether temp is True or False outside of the loop.

Number is not a prime number if it is True.
If False, the given number is a prime number.

2)Using For Else Statement

To check if number is prime, we used a for…else argument.

It is based on the logic that the for loop’s else statement runs if and only if the for loop is not broken out. Only when no variables are found is the condition satisfied, indicating that the given number is prime.

As a result, we print that the number is prime in the else clause.

Below is the implementation:

# given number
number = 5

# We will check if the number is greater than 1 or not
# since prime numbers starts from 2
if number > 1:
    # checking the divisors of the number
    for i in range(2, number):
        if (number % i) == 0:
            # if any divisor is found then print it is not prime
            print("The given number", number, "is not prime number")
            # Break the loop if it is not prime
            break
    else:
        print("The given number", number, "is prime number")
# if the number is less than 1 then print it is not prime number
else:
    print("The given number", number, "is not prime number")

Output:

The given number 5 is prime number

3)Limitations of above methods in terms of Time Complexity

In these two methods the loop runs from 2 to number N-1.

Hence we can say that the time complexity of above methods are O(n).

What if the number is very large?

Like 10^18 the above methods takes nearly 31 years to execute.

Then How to avoid this?

We can see that the factors of the numbers exist from 1 to N/2 except number itself.

But this also takes nearly 15 yrs to execute.

So to above this we loop till square root of N in next method which gives Time Complexity O(Sqrt(n)).

4)Solution Approach for Efficient Approach

We will improve our program by reducing the number range in which we search for factors.

Our search range in the above program is 2 to number – 1.

The set, range(2,num/2) or range(2,math.floor(math.sqrt(number)) should have been used. The latter range is based on the requirement that a composite number’s factor be less than its square root. Otherwise, it’s a prime number.

5)Implementation of Efficient Approach

In this function, we use Python’s math library to calculate an integer, max_divisor, that is the square root of the number and get its floor value. We iterate from 2 to n-1 in the last example. However, we reduce the divisors by half in this case, as shown. To get the floor and sqrt functions, you’ll need to import the math module.
Approach:

  • If the integer is less than one, False is returned.
  • The numbers that need to be verified are now reduced to the square root of the given number.
  • The function will return False if the given number is divisible by any of the numbers from 2 to the square root of the number.
  • Otherwise, True would be returned.

Below is the implementation:

# importing math module
import math
# function which returns True if the number is prime else not


def checkPrimeNumber(number):
    if number < 1:
        return False
    # checking the divisors of the number
    max_divisor = math.floor(math.sqrt(number))
    for i in range(2, max_divisor+1):
        if number % i == 0:
            # if any divisor is found then return False
            return False
        # if no factors are found then return True
        return True


# given number
number = 5
# passing number to checkPrimeNumber function
if(checkPrimeNumber(number)):
    print("The given number", number, "is prime number")
else:
    print("The given number", number, "is not prime number")

Output:

The given number 5 is prime number

Related Programs:

Python quadratic formula – Python Program to Solve Quadratic Equation

Python Program to Solve Quadratic Equation

Solve Quadratic Equation using Python

Quadratic equation in python: Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Quadratic Equation

Python quadratic formula: Quadratics or quadratic equations are polynomial equations of the second degree, which means that they contain at least one squared word.

ax2 + bx + c = 0

where x is an unknown variable and the numerical coefficients a , b , c.

2)Discriminant value

Discriminant = b ^ 2 - 4 * a *c

Based on the value of discriminant there are three types of roots for Quadratic Equation

3)Calculating roots of Quadratic Equation

roots = ( -b + sqrt(b ^ 2 - 4 * a *c) ) / (2 * a)   , ( -b - sqrt(b ^ 2 - 4 * a *c) ) / (2 * a)

Where sqrt is square root.

4)Types of roots

i)Real and distinct roots

When the Value of discriminant is greater than 0 then there exist two distinct roots for the quadratic equation

which can be calculated using the above roots formula.

Examples:

Input:

a = 2
b = -7
c = 6

Output:

The two distinct roots are : 
(2+0j)
(1.5+0j)

ii)Real and equal roots

When the Value of discriminant is equal to 0 then there exist two equal roots for the quadratic equation .

which can be calculated using the above roots formula.

Examples:

Input:

a = 1
b = -4
c = 4

Output:

The two equal roots are : 
2.0 2.0

iii)Complex roots

When the Value of discriminant is greater than 0 then there exist two complex roots for the quadratic equation .

which can be calculated using the above roots formula.

Examples:

Input:

a = 5
b = 2
c = 3

Output:

There exists two complex roots:
(-1+1.7320508075688772j)
(-1-1.7320508075688772j)

5)Approach

  • To perform complex square root, we imported the cmath module.
  • First, we compute the discriminant.
  • Using if..elif..else we do the below steps
  • If the value of discriminant is  greater than 0 then we print real roots using mathematical formula.
  • If the value of discriminant is  equal to 0 then we print two equal roots using mathematical formula.
  • If the value of discriminant is  less than 0 then we print two complex roots using mathematical formula.

6)Implementation:

Below is the implementation:

# importing cmath
import cmath
# given a,b,c values
a = 2
b = -7
c = 6
discriminant = (b**2) - (4*a*c)
# checking if the value of discriminant is greater than 0
if(discriminant > 0):
    # here exist the two distinct roots and we print them
    # calculating the roots
    root1 = (-b+discriminant) / (2 * a)
    root2 = (-b-discriminant) / (2 * a)
    # printing the roots

    print("The two distinct roots are : ")
    print(root1)
    print(root2)
# checking if the value of discriminant is equal to 0
elif(discriminant == 0):
    # here exist the two equal roots
    # calculating single root here discriminant is 0 so we dont need to write full formulae
    root = (-b)/(2*a)
    # printing the root
    print("The two equal roots are : ")
    print(root, root)
# else there exists complex roots
else:
    # here exist the two complex roots
    # calculating complex roots
    realpart = -b/(2*a)
    complexpart = discriminant/(2*a)*(-1)
    # printing the roots
    print("There exists two complex roots:")
    print(realpart, "+", complexpart, "i")
    print(realpart, "-", complexpart, "i")

Output:

The two distinct roots are : 
(2+0j)
(1.5+0j)

Related Programs:

Python read() method – Python File read() Method with Examples

file-read()-method-with-examples

Files In Python:

Python read() method: A file is a piece of data or information stored on a computer’s hard drive. You’re already familiar with a variety of file kinds, including music, video, and text files. Manipulation of these files is trivial with Python. Text files and binary files are the two types of files that are commonly used. Binary files contain binary data that can only be read by a computer, whereas text files include plain text.

For programmers and automation testers, Python file handling (also known as File I/O) is a crucial topic. Working with files is required in order to write to or read data from them.

In addition, if you didn’t know, I/O activities are the most expensive techniques via which software might fail. As a result, when implementing file processing for reporting or any other reason, you should proceed with caution. The construction of a high-performance application or a robust solution for automated software testing can benefit from optimizing a single file activity.

File read() Method in Python:

Python read method: The read() method is a built-in method in Python that is used to read the content of a file.

The read() method reads the specified number of bytes from the file and returns them. The default value is -1, which means the entire file.

Syntax:

file.read()

Parameters

size: This is optional. The number of bytes that will be returned. The default value is -1, which means the entire file.

Return Value:

Read method python: This method’s return type is <class’str’>; it returns the string, i.e. the file’s content (if the file is in text mode).

File read() Method with Examples in Python

Example1

Approach:

  • 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.
  • Open the file in read mode. In this case, we’re simply reading the contents of the file.
  • Read the contents of the file using the read() function and print it.
  • The Exit of Program.

Below is the implementation:

# 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 mode. In this case, we're simply reading the contents of the file.
read_file = open(givenFilename, 'r') 
# Read the contents of the file using the read() function and print it
print(read_file.read())

Output:

hello this is btechgeeks 
good morning btechgeeks
welcome all

Example2

Approach:

  • 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.
  • Open the file in read mode. In this case, we’re simply reading the contents of the file.
  • Pass some random number to the read() function to read the specified number of bytes of the file and print it.
  • The Exit of Program.

Below is the implementation:

# 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 mode. In this case, we're simply reading the contents of the file.
read_file = open(givenFilename, 'r') 
# Pass some random number to the read() function to read the specified number
# of bytes of the file and print it.
print(read_file.read(20))

Output Text:

hello this is btechg

File Content:

hello this is btechgeeks 
good morning btechgeeks
welcome all

Google Colab Images:

Files and Code:

Pandas series mode – Python Pandas Series mode() Function

Python Pandas Series mode() Function

Pandas Series mode() Function:

Pandas series mode: The mode() function of the Pandas Series returns the mode/modes of the given Series.

Syntax:

Series.mode(dropna=None)

Parameters

dropna: This is optional. When computing the result, specify True to exclude NA/null values. True is the default value.

Return Value:

Mode pandas: The mode/modes of the Series in sorted order is returned by the mode() function of the Pandas Series

Pandas Series mode() Function in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Import numpy module using the import keyword.
  • Give the category(level) values as arguments list to from_arrays() functions
  • Pass some random list, index values from the above and name as Numbers as the arguments to the Series() function of the pandas module to create a series.
  • Store it in a variable.
  • Print the above-given series
  • Apply mode() function on the given series to get the mode values of all the elements of the given series and print the result.
  • 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
# Give the category(level) values as arguments list to from_arrays() functions
gvn_indx = pd.MultiIndex.from_arrays([
    ['positive', 'negative', 'positive', 
     'positive', 'negative', 'negative']],
    names=['DataType'])
# Pass some random list, index values from the above and name as Numbers
# as the arguments to the Series() function of the pandas module to create a series.
# Store it in a variable.
gvn_series = pd.Series([12, 3, 12, 14, 56, 3], 
              name='Numbers', index=gvn_indx)

# Print the above given series
print("The given series is:")
print(gvn_series)
print()
# Apply mode() function on the given series to
# get the mode values of all the elements of the given series
# and print the result.
print("The mode values of all the elements of the given series:")
print(gvn_series.mode())

Output:

The given series is:
DataType
positive    12
negative     3
positive    12
positive    14
negative    56
negative     3
Name: Numbers, dtype: int64

The mode values of all the elements of the given series:
0     3
1    12
dtype: int64

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 mode() function on the student_marks column of the dataframe to get the mode of the student_marks column of the dataframe 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 mode() function on the student_marks column of the dataframe to
# get the mode of the student_marks column of the dataframe
# and print the result.
print("The mode of student_marks column of the dataframe:")
print(data_frme["student_marks"].mode())

Output:

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

The mode of student_marks column of the dataframe:
0    25
1    35
2    80
3    90
dtype: int64

 

Python count word frequency dictionary – Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary

Program to Count the Frequency of Words Appearing in a String Using a Dictionary

Dictionaries in Python:

Python count word frequency dictionary: Dictionary is a mutable built-in Python Data Structure. It is conceptually related to List, Set, and Tuples. It is, however, indexed by keys rather than a sequence of numbers and can be thought of as associative arrays. On a high level, it consists of a key and its associated value. The Dictionary class in Python represents a hash-table implementation.

Examples:

Example1:

Input:

given string ="hello this is hello BTechGeeks BTechGeeks BTechGeeks this python programming python language"

Output:

{'hello': 2, 'this': 2, 'is': 1, 'BTechGeeks': 3, 'python': 2, 'programming': 1, 'language': 1}

Example2:

Input:

given string ="good morning this is good this python python BTechGeeks good good python online coding platform"

Output:

{'good': 4, 'morning': 1, 'this': 2, 'is': 1, 'python': 3, 'BTechGeeks': 1, 'online': 1, 'coding': 1, 'platform': 1}

Program to Count the Frequency of Words Appearing in a String Using a Dictionary

There are several ways to count the frequency of all words in the given string using dictionary some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using count and zip function (Static Input)

Approach:

  • Give the string input as static and store it in a variable
  • Split the given string into words using split() function
  • Convert this into list using list() function.
  • Count the frequency of each term using count() function and save the results in a separate list using list Comprehension.
  • Merge the lists containing the terms and the word counts into a dictionary using the zip() function.
  • The resultant dictionary is printed
  • End of Program

Below is the implementation:

# given string
given_string = "hello this is hello BTechGeeks BTechGeeks BTechGeeks this python programming python language"
# Split the given string into words using split() function
# Convert this into list using list() function.
listString = given_string.split()
# Count the frequency of each term using count() function and
# save the results in a separate list using list Comprehension.
freqWords = [listString.count(k) for k in listString]
# Merge the lists containing the terms and the word counts
# into a dictionary using the zip() function.
resultdict = dict(zip(listString, freqWords))
# Print the resultant dictionary
print(resultdict)

Output:

{'hello': 2, 'this': 2, 'is': 1, 'BTechGeeks': 3, 'python': 2, 'programming': 1, 'language': 1}

Explanation:

  • A string must be entered by the user and saved in a variable.
  • The string is divided into words and saved in the list using a space as the reference.
  • Using list comprehension and the count() function, the frequency of each word in the list is counted.
  • The complete dictionary is printed after being created with the zip() method.

Method #2:Using count and zip function (User Input)

Approach:

  • Scan the string using input() function.
  • Split the given string into words using split() function
  • Convert this into list using list() function.
  • Count the frequency of each term using count() function and save the results in a separate list using list Comprehension.
  • Merge the lists containing the terms and the word counts into a dictionary using the zip() function.
  • The resultant dictionary is printed
  • End of Program

Below is the implementation:

# Scan the given string using input() function
given_string = input("Enter some random string separated by spaces = ")
# Split the given string into words using split() function
# Convert this into list using list() function.
listString = given_string.split()
# Count the frequency of each term using count() function and
# save the results in a separate list using list Comprehension.
freqWords = [listString.count(k) for k in listString]
# Merge the lists containing the terms and the word counts
# into a dictionary using the zip() function.
resultdict = dict(zip(listString, freqWords))
# Print the resultant dictionary
print(resultdict)

Output:

Enter some random string separated by spaces = good morning this is good this python python BTechGeeks good good python online coding platform
{'good': 4, 'morning': 1, 'this': 2, 'is': 1, 'python': 3, 'BTechGeeks': 1, 'online': 1, 'coding': 1, 'platform': 1}

Related Programs:

Pandas div – Python Pandas DataFrame div() Function

Python Pandas DataFrame div() Function

Pandas div: 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 div() Function:

Pandas div: The div() function of the Pandas module returns the element-wise floating division of a dataframe and other. It’s similar to dataframe / other, but with the ability to provide a fill_value as one of the parameters to replace missing data.

Syntax:

DataFrame.div(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 div() Function in Python

Example1

Here, to divide the entire DataFrame by a scalar value, we used the div() 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 div() function to the dataframe by passing some random number to it and print the result.
  • Here it divides the entire dataframe by 5.
  • 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 div() function to the dataframe by passing some random number
# to it and print the result.
# Here it divides the entire dataframe by 5.
print("The result dataframe after dividing the entire dataframe by 5:")
print(data_frme.div(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 dividing the entire dataframe by 5:
        student_rollno  student_marks
virat              0.2           16.0
nick               0.4            7.0
jessy              0.6            5.0
sindhu             0.8           18.0

Example2

Here, the ‘other’ argument can be provided as a list to divide different columns by 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 div() function to the dataframe by passing list as an argument to it which divides elements of the dataframe by corresponding list elements and print the result.
  • Here it divides the student_rollno column of the dataframe by 2 and student_marks column of the dataframe by 10.
  • 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 div() function to the dataframe by passing list as an argument to it 
# which divides elements of the dataframe by corresponding list elements and print the result.
# Here it divides the student_rollno column of the dataframe by 2
# and student_marks column of the dataframe by 10.
print("The dataframe after dividing student_rollno by 2, student_marks by 10:")
print(data_frme.div([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 dividing student_rollno by 2, student_marks by 10:
        student_rollno  student_marks
virat              0.5            8.0
nick               1.0            3.5
jessy              1.5            2.5
sindhu             2.0            9.0

Example3

Here, div() 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 div() function to the specified column of dataframe by passing some random number to it and print the result.
  • Here it divides the student_rollno column by 5
  • Apply div() function to the specified columns of dataframe which divides elements of the specified columns by corresponding list elements and print the result.
  • Here it divides the student_rollno column of the dataframe by 2 and student_marks column of the dataframe by 10.
  • 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 div() function to the specified column of dataframe by passing some random number
# to it and print the result.
# Here it divides the student_rollno column by 5
print("The dataframe after dividing the student_rollno column by 5:")
print(data_frme["student_rollno"].div(5))
print()

# Apply div() function to the specified columns of dataframe which divides elements
# of the specified columns by corresponding list elements and print the result.
# Here it divides the student_rollno column of the dataframe by 2.
# and student_marks column of the dataframe by 10.
print("The dataframe after dividing student_rollno by 2, student_marks by 10:")
print(data_frme[["student_rollno", "student_marks"]].div([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 dividing the student_rollno column by 5:
virat     0.2
nick      0.4
jessy     0.6
sindhu    0.8
Name: student_rollno, dtype: float64

The dataframe after dividing student_rollno by 2, student_marks by 10:
        student_rollno  student_marks
virat              0.5            8.0
nick               1.0            3.5
jessy              1.5            2.5
sindhu             2.0            9.0

Example4

In a DataFrame, the div() function can be used to obtain the floating division of two series/column elements.

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.
  • Divide the column student_marks by student_rollno using the div() function and store it as a new column in the dataframe.
  • Print the dataframe after adding a new column(student_marks / student_rollno).
  • 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()

# Divide the column student_marks by student_rollno using the div() 
# function and store it as a new column in the dataframe.
data_frme['student_marks / student_rollno'] = data_frme['student_marks'].div(data_frme['student_rollno'])
# Print the dataframe after adding a new column(student_marks / student_rollno)
print("The DataFrame after adding a new column(student_marks / student_rollno):")
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_marks / student_rollno):
        student_rollno  student_marks  student_marks / student_rollno
virat                1             80                       80.000000
nick                 2             35                       17.500000
jessy                3             25                        8.333333
sindhu               4             90                       22.500000