Python Program to Print all the Prime Numbers within a Given Range

Program to Print all the Prime Numbers within a Given Range

Given the upper limit range, the task is to print all the prime numbers in the given range in Python.

Examples:

Example1:

Input:

given number = 95

Output:

The prime numbers from 2 to upper limit [ 95 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89

Example2:

Input:

given number = 52

Output:

Enter some random upper limit range = 52
The prime numbers from 2 to upper limit [ 52 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Python Program to Print all the Prime Numbers within a Given Range

There are several ways to print all the prime numbers from 2 to the upper limit range some of them are:

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Method #1:Using for loop(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Set the first for loop to have a range of 2 to the upper limit range.
  • Take a temporary variable which is the count variable and initialize it to zero.
  • Allow the second for loop to have a range of 2 to half the number (excluding 1 and the number itself).
  • Then, using the if statement, determine the number of divisors and increment the count variable each time.
  • The number is prime if the number of divisors is lower than or equal to zero.
  • Prime numbers till the given upper limit range are printed.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
givenNumbr = 95
print('The prime numbers from 2 to upper limit [', givenNumbr, '] :')
# Set the first for loop to have a range of 2 to the upper limit range.
for valu in range(2, givenNumbr+1):
  # Take a temporary variable which is the count variable and initialize it to zero.
    cntvar = 0
    # Allow the second for loop to have a range of 2 to
    # half the number (excluding 1 and the number itself).
    for divi in range(2, valu//2+1):
      # Then, using the if statement, determine the number of divisors
      # and increment the count variable each time.
        if(valu % divi == 0):
            cntvar = cntvar+1
    # The number is prime if the number of divisors is lower than or equal to zero.
    if(cntvar <= 0):
        print(valu, end=' ')

Output:

The prime numbers from 2 to upper limit [ 95 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89

All the prime numbers till the upper limit range are printed.

Method #2:Using for loop(User Input)

Approach:

  • Give the number as user input with the help of the int(input()) function and store it in a variable.
  • Set the first for loop to have a range of 2 to the upper limit range.
  • Take a temporary variable which is the count variable and initialize it to zero.
  • Allow the second for loop to have a range of 2 to half the number (excluding 1 and the number itself).
  • Then, using the if statement, determine the number of divisors and increment the count variable each time.
  • The number is prime if the number of divisors is lower than or equal to zero.
  • Prime numbers till the given upper limit range are printed.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input with the help
# of the int(input()) function and store it in a variable.
givenNumbr = int(input('Enter some random upper limit range = '))
print('The prime numbers from 2 to upper limit [', givenNumbr, '] :')
# Set the first for loop to have a range of 2 to the upper limit range.
for valu in range(2, givenNumbr+1):
  # Take a temporary variable which is the count variable and initialize it to zero.
    cntvar = 0
    # Allow the second for loop to have a range of 2 to
    # half the number (excluding 1 and the number itself).
    for divi in range(2, valu//2+1):
      # Then, using the if statement, determine the number of divisors
      # and increment the count variable each time.
        if(valu % divi == 0):
            cntvar = cntvar+1
    # The number is prime if the number of divisors is lower than or equal to zero.
    if(cntvar <= 0):
        print(valu, end=' ')

Output:

Enter some random upper limit range = 52
The prime numbers from 2 to upper limit [ 52 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Explanation:

  • The user must enter the range’s upper limit and save it in a separate variable.
  • The first for loop runs until the user enters an upper limit.
  • The count variable is initially set to 0.
  • Because the for loop runs from 2 to half of the number, 1 and the number itself is not considered divisors.
  • If the remainder is equal to zero, the if statement looks for the number’s divisors.
  • The count variable counts the number of divisors, and if the count is less than or equal to zero, the integer is prime.
  • If the count exceeds zero, the integer is not prime.
  • All the prime numbers till the upper limit range are printed.

Related Programs:

Python Program to Search the Number of Times a Particular Number Occurs in a List

Program to Search the Number of Times a Particular Number Occurs in a List

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Lists in Python:

The Python list is a straightforward ordered list of items. Python lists are extremely powerful since the objects in them do not have to be homogeneous or even of the same type. Strings, numbers, and characters, as well as other lists, can all be found in a Python list. Python lists are also mutable: once stated, they can be easily altered via a variety of list methods. Let’s look at how to use these techniques to handle Python lists.

Given a list and a element, the task is to write a  Python Program to Determine the Number of Occurrences of a Specific Number in a given List

Examples:

Examples1:

Input:

given list = ["my", "name", "is", "BTechGeeks", "coding", "platform", "for", "BTechGeeks"]

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Examples2:

Input:

given list = [5, 9, 1, 3, 6, 9, 2, 12, 8]

Output:

The count of the element ' 9 ' in the list [5, 9, 1, 3, 6, 9, 2, 12, 8] = 2

Python Program to Search the Number of Times a Particular Number Occurs in a List

There are several ways to determine the Number of Occurrences of a Specific Number in a given List some of them are:

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.

Method #1: Using a Counter Variable

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Take a variable which stores the count of the element say countEleme and initialize it to 0.
  • Traverse the given list using for loop.
  • If the iterator element is equal to the given element.
  • Then increment the countEleme value by 1.
  • Print the countEleme.

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Take a variable which stores the count of the element
# say totalCount and initialize it to 0.
countEleme = 0
# Traverse the given list using for loop.
for value in given_list:
    # if the value is equal too given_element then increase the countEleme by 1
    if(value == given_element):
        countEleme = countEleme+1
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #2: Using Count() function

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Count the given element in the list using count() function.
  • Print the countEleme.

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Count the given element in the list using count() function.
countEleme = given_list.count(given_element)
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #3: Using Counter() function

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Use Counter function which stores the frequency as values and element as keys in its dictionary
  • Print the value of the given element

Below is the implementation:

# importing counter function from collections
from collections import Counter
# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Using counter function
freqValues = Counter(given_list)
# Count the given element in the list
countEleme = freqValues[given_element]
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #4:Using List Comprehension

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Using list Comprehension checking if given element is equal to the iterator value
  • The count of the length of this new list gives the required answer

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Using list comprehension
elementlist = [eleme for eleme in given_list if eleme == given_element]

# Count the given element in the list using len function
countEleme = len(elementlist)
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Pandas: Add Two Columns into a New Column in Dataframe

Methods to add two columns into a new column in Dataframe

In this article, we discuss how to add to column to an existing column in the dataframe and how to add two columns to make a new column in the dataframe using pandas. We will also discuss how to deal with NaN values.

  • Method 1-Sum two columns together to make a new series

In this method, we simply select two-column by their column name and then simply add them.Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, np.NaN, 81) , 
            ('Abhay', 25,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
total = df['Age'] + df['Marks']
print("New Series \n") 
print(total)
print(type(total))

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22        NaN     81
3  Abhay   25  Rajasthan     90
4  Ajjet   21      Delhi     74 

New Series 

0    119
1    118
2    103
3    115
4     95
dtype: int64
<class 'pandas.core.series.Series'>

Here we see that when we add two columns then a series will be formed.]

Note: We can’t add a string with int or float. We can only add a string with a string or a number with a number.

Let see the example of adding string with string.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', 81) , 
            ('Abhay', 25,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
total = df['Name'] + " "+df['City']
print("New Series \n") 
print(total)
print(type(total))

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     81
3  Abhay   25  Rajasthan     90
4  Ajjet   21      Delhi     74 

New Series 

0         Raj Mumbai
1        Rahul Delhi
2       Aadi Kolkata
3    Abhay Rajasthan
4        Ajjet Delhi
dtype: object
<class 'pandas.core.series.Series'>
  • Method 2-Sum two columns together having NaN values to make a new series

In the previous method, there is no NaN or missing values but in this case, we also have NaN values. So when we add two columns in which one or two-column contains NaN values then we will see that we also get the result as NaN. Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', np.NaN) , 
            ('Abhay', np.NaN,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
total = df['Marks'] + df['Age']
print("New Series \n") 
print(total)
print(type(total))

Output

Original Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0    Kolkata    NaN
3  Abhay   NaN  Rajasthan   90.0
4  Ajjet  21.0      Delhi   74.0 

New Series 

0    119.0
1    118.0
2      NaN
3      NaN
4     95.0
dtype: float64
<class 'pandas.core.series.Series'>
  • Method 3-Add two columns to make a new column

We know that a dataframe is a group of series. We see that when we add two columns it gives us a series and we store that sum in a variable. If we make that variable a column in the dataframe then our work will be easily done. Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
('Rahul', 21, 'Delhi' , 97) , 
('Aadi', 22, 'Kolkata',76) , 
('Abhay',23,'Rajasthan' , 90) , 
('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
df['total'] = df['Marks'] + df['Age']
print("New Dataframe \n") 
print(df)
 
print(df)

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     76
3  Abhay   23  Rajasthan     90
4  Ajjet   21      Delhi     74 

New Dataframe 

    Name  Age       City  Marks  total
0    Raj   24     Mumbai     95    119
1  Rahul   21      Delhi     97    118
2   Aadi   22    Kolkata     76     98
3  Abhay   23  Rajasthan     90    113
4  Ajjet   21      Delhi     74     95
  • Method 4-Add two columns with NaN values to make a new column

The same is the case with NaN values. But here NaN values will be shown.Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', np.NaN) , 
            ('Abhay', np.NaN,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
df['total'] = df['Marks'] + df['Age']
print("New Dataframe \n") 
print(df)

Output

Original Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0    Kolkata    NaN
3  Abhay   NaN  Rajasthan   90.0
4  Ajjet  21.0      Delhi   74.0 

New Dataframe 

    Name   Age       City  Marks  total
0    Raj  24.0     Mumbai   95.0  119.0
1  Rahul  21.0      Delhi   97.0  118.0
2   Aadi  22.0    Kolkata    NaN    NaN
3  Abhay   NaN  Rajasthan   90.0    NaN
4  Ajjet  21.0      Delhi   74.0   95.0

So these are the methods to add two columns in the dataframe.

Matplotlib: Line plot with markers

Methods to draw line plot with markers with the help of Matplotlib

In this article, we will discuss some basics of matplotlib and then discuss how to draw line plots with markers.

Matplotlib

We know that data that is in the form of numbers is difficult and boring to analyze. But if we convert that number into graphs, bar plots, piecharts, etc then it will be easy and interesting to visualize the data. Here Matplotlib library of python came into use. Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.

For using this library we have to first import it into the program. For importing this we can use

from matplotlib import pyplot as plt or import matplotlib. pyplot as plt.

In this article, we only discuss the line plot. So let see the function in matplotlib to draw a line plot.

syntax:  plt.plot(x,y, scalex=True, scaley=True, data=None, marker=’marker style’, **kwargs)

Parameters

  1. x,y: They represent vertical and horizontal axis.
  2. scalex, scaley: These parameters determine if the view limits are adapted to the data limits. The default value is True.
  3. marker: It contains types of markers that can be used. Like point marker, circle marker, etc.

Here is the list of markers used in this

  • “’.’“           point marker
  • “’,’“           pixel marker
  • “’o’“          circle marker
  • “’v’“          triangle_down marker
  • “’^’“          triangle_up marker
  • “'<‘“          triangle_left marker
  • “’>’“          triangle_right marker
  • “’1’“          tri_down marker
  • “’2’“          tri_up marker
  • “’3’“          tri_left marker
  • “’4’“          tri_right marker
  • “’s’“          square marker
  • “’p’“          pentagon marker
  • “’*’“          star marker
  • “’h’“          hexagon1 marker
  • “’H’“         hexagon2 marker
  • “’+’“          plus marker
  • “’x’“          x marker
  • “’D’“         diamond marker
  • “’d’“          thin_diamond marker
  • “’|’“           vline marker
  • “’_’“          hline marker

Examples of Line plot with markers in matplotlib

  • Line Plot with the Point marker

Here we use marker='.'.Let see this with the help of an example.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,40,.5)
y = np.sin(x)
plt.plot(x,y, marker='.')
plt.title('Sin Function')
plt.xlabel('x values')
plt.ylabel('y= sin(x)')
plt.show()

Output

  • Line Plot with the Point marker and give marker some color

In the above example, we see the color of the marker is the same as the color of the line plot. So there is an attribute in plt.plot() function marker face color or mfc: color which is used to give color to the marker. Let see this with the help of an example.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,40,.5)
y = np.sin(x)
plt.plot(x,y, marker='.',mfc='red')
plt.title('Sin Function')
plt.xlabel('x values')
plt.ylabel('y= sin(x)')
plt.show()

Output

Here we see that color of the pointer changes to red.

  • Line Plot with the Point marker and change the size of the marker

To change the size of the marker there is an attribute in pointer ply.plot() function that is used to achieve this. marker size or ms attribute is used to achieve this. We can pass an int value in ms and then its size increases or decreases according to this. Let see this with the help of an example.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,40,.5)
y = np.sin(x)
plt.plot(x,y, marker='.',mfc='red',ms='17')
plt.title('Sin Function')
plt.xlabel('x values')
plt.ylabel('y= sin(x)')
plt.show()

Output

Here we see that size of the pointer changes.

  • Line Plot with the Point marker and change the color of the edge of the marker

We can also change the color of the edge of marker with the help of markeredgecolor or mec attribute. Let see this with the help of an example.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,40,.5)
y = np.sin(x)
plt.plot(x,y, marker='.',mfc='red',ms='17', mec='yellow')
plt.title('Sin Function')
plt.xlabel('x values')
plt.ylabel('y= sin(x)')
plt.show()

Output

Here we see that the color of the edge of the pointer changes to yellow.

So here are some examples of how we can work with markers in line plots.

Note: These examples are applicable to any of the marker.

Get Rows And Columns Names In Dataframe Using Python

Methods to get rows and columns names in dataframe

In this we will study different methods to get rows and column names in a dataframe.

Methods to get column name in dataframe

  • Method 1: By iterating over columns

In this method, we will simply be iterating over all the columns and print the names of each column. Point to remember that dataframe_name. columns give a list of columns.Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', 81) , 
            ('Abhay', 24,'Rajasthan' ,76) , 
              ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n')
print(df.columns,'\n')
print("columns are:")
for column in df.columns:
  print(column,end=" ")

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     81
3  Abhay   24  Rajasthan     76
4  Ajjet   21      Delhi     74 

Index(['Name', 'Age', 'City', 'Marks'], dtype='object') 

columns are:
Name Age City Marks 

Here we see that df. columns give a list of columns and by iterating over this list we can easily get column names.

  • Method 2-Using columns.values

columns. values return an array of column names. Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', 81) , 
            ('Abhay', 24,'Rajasthan' ,76) , 
              ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n')
print("columns are:")
print(df.columns.values,'\n')

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     81
3  Abhay   24  Rajasthan     76
4  Ajjet   21      Delhi     74 

columns are:
['Name' 'Age' 'City' 'Marks'] 
  • Method 3- using tolist() method

Using tolist() method with values with given the list of columns. Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', 81) , 
            ('Abhay', 24,'Rajasthan' ,76) , 
              ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n')
print("columns are:")
print(df.columns.values.tolist(),'\n')

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     81
3  Abhay   24  Rajasthan     76
4  Ajjet   21      Delhi     74 

columns are:
['Name', 'Age', 'City', 'Marks'] 
  • Method 4- Access specific column name using index

As we know that columns. values give an array of columns and we can access array elements using an index. So in this method, we use this concept. Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', 81) , 
            ('Abhay', 24,'Rajasthan' ,76) , 
              ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n')
print("columns at second index:")
print(df.columns.values[2],'\n')

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     81
3  Abhay   24  Rajasthan     76
4  Ajjet   21      Delhi     74 

columns at second index:
City 

So these are the methods to get column names.

Method to get rows name in dataframe

  • Method 1-Using index.values

As columns., values give a list or array of columns similarly index. values give a list of array of indexes. Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', 81) , 
            ('Abhay', 24,'Rajasthan' ,76) , 
              ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n')
print("Rows are:")
print(df.index.values,'\n')

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     81
3  Abhay   24  Rajasthan     76
4  Ajjet   21      Delhi     74 

Rows are:
[0 1 2 3 4] 
  • Method 2- Get Row name at a specific index

As we know that index. values give an array of indexes and we can access array elements using an index. So in this method, we use this concept. Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) , 
('Rahul', 21, 'Delhi' , 97) , 
('Aadi', 22, 'Kolkata', 81) , 
('Abhay', 24,'Rajasthan' ,76) , 
('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n')
print("Row at index 2:")
print(df.index.values[2],'\n')

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     81
3  Abhay   24  Rajasthan     76
4  Ajjet   21      Delhi     74 

Row at index 2:
2 
  • Method 3-By iterating over indices

As dataframe_names.columns give a list of columns similarly dataframe_name.index gives the list of indexes. Hence we can simply be iterating over all lists of indexes and print rows names. Let see this with help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', 81) , 
            ('Abhay', 24,'Rajasthan' ,76) , 
              ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n')
print("List of indexes:")
print(df.index,'\n')
print("Indexes or rows names are:")
for row in df.index:
  print(row,end=" ")

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     81
3  Abhay   24  Rajasthan     76
4  Ajjet   21      Delhi     74 

List of indexes:
RangeIndex(start=0, stop=5, step=1) 

Indexes or rows names are:
0 1 2 3 4 

So these are the methods to get rows and column names in the dataframe using python.

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

Read more Articles on Python Data Analysis Using Padas – Select items from a Dataframe

Python Program to Find the Number of Weeks between two Dates

Program to Find the Number of Weeks between two Dates

In the previous article, we have discussed Python Program to Print all Disarium Numbers within Given range
DateTime:

It is a date and time combination with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.

Date and time are not data types in Python, but a module called DateTime can be imported to work with both the date and the time. There is no need to install the Datetime module externally because it is built into Python.

The Datetime module includes classes for working with dates and times. These classes offer a variety of functions for working with dates, times, and time intervals. In Python, date and DateTime are objects, so when you manipulate them, you are actually manipulating objects rather than strings or timestamps.

Given two dates, and the task is to find the number of weeks between the given two dates.

Examples:

Example1:

Input:

Given First date =2003-11- 10  (YY-MM-DD)
Given second date=2007-4- 12

Output:

The number of weeks between two given dates =  178

Example 2:

Input:

Given First date =1998-5-16 (YY-MM-DD)
Given second date=2001-7- 9

Output:

The number of weeks between two given dates =  164

Program to Find the Number of Weeks between two Dates

Below are the ways to Find the Number of Weeks between two Dates.

Method #1: Using DateTime Module (Static input)

Approach:

  • Import DateTime module using date keyword.
  • Give the First date as static input in the format of YY, MM, DD, and store it in a variable.
  • Give the Second date as static input in the format of YY, MM, DD and store it in another variable.
  • Calculate the absolute difference between the above given two dates using abs(date1-date2) and store it in another variable.
  • Divide the above-got number of days by 7, using the floor division operator, and store it in another variable.
  • Print the number of weeks between the two above given dates.
  • The Exit of the program.

Below is the implementation:

# Import datetime module using date keyword.
from datetime import date
# Give the First date as static input in the format of YY,MM,DD and store it in a variable.
fst_dat_1 = date(2003, 11, 10)
# Give the Second date as static input in the format of YY,MM,DD and store it in another variable.
secnd_dat_2 = date(2007, 4, 12)
# Calculate the absolute difference between the above given two dates using
# abs(date1-date2) and store it in another variable.
no_dayss = abs(fst_dat_1-secnd_dat_2).days
# Divide the above got number of days by 7 ,using floor division operator and
# store it in another variable.
no_weks = no_dayss//7
# Print the number of weeks between  two  above given dates.
print(" The number of weeks between two given dates = ", no_weks)

Output:

The number of weeks between two given dates = 178

Method #2: Using DateTime Module (User input)

Approach:

  • Import DateTime module using date keyword.
  • Give the First date as user input in the format of YY, MM, DD as a string using input(), int(), split() functions function and store it in a variable.
  • Give the Second date as user input in the format of YY, MM, DD as a string using input(), int(), split() functions and store it in another variable.
  • Calculate the absolute difference between the above given two dates using abs(date1-date2) and store it in another variable.
  • Divide the above-got number of days by 7, using the floor division operator, and store it in another variable.
  • Print the number of weeks between the two above given dates.
  • The Exit of the program.

Below is the implementation:

# Import datetime module using date keyword.
from datetime import date
# Give the First date as user input in the format of YY, MM, DD
# as a string using input(),int(),split() functions and store it in a variable.
yy1, mm1, dd1 = map(int, input(
    'Enter year month and date separated by spaces = ').split())
fst_dat_1 = date(yy1, mm1, dd1)
# Give the Second date as user  input using input(),int(),split() functions
# in the format of YY,MM,DD and store it in another variable.
yy2, mm2, dd2 = map(int, input(
    'Enter year month and date separated by spaces = ').split())
secnd_dat_2 = date(yy2, mm2, dd2)
# Calculate the absolute difference between the above given two dates using
# abs(date1-date2) and store it in another variable.
no_dayss = abs(fst_dat_1-secnd_dat_2).days
# Divide the above got number of days by 7 ,using floor division operator and
# store it in another variable.
no_weks = no_dayss//7
# Print the number of weeks between  two  above given dates.
print(" The number of weeks between two given dates = ", no_weks)

Output:

Enter year month and date separated by spaces = 2001 02 11
Enter year month and date separated by spaces = 2001 09 28
The number of weeks between two given dates = 32

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.

Python Program to Find Vertex, Focus and Directrix of Parabola

Program to Find Vertex, Focus and Directrix of Parabola

In the previous article, we have discussed Python Program to Print nth Iteration of Lucas Sequence
Parabola:

A parabola is a curve in a 2D plane that is the same distance from a fixed point called focus as a fixed straight line. The directrix is the name given to this line. A parabola’s general equation is y= ax2+bx+c. In this case, a, b, and c can be any real number.

Given a, b, c  values, the task is to determine Vertex, Focus, and Directrix of the above Given Parabola.

Examples:

Example 1 :

Input :

Given first Term = 5
Given second Term = 2
Given Third Term = 3

Output:

The Vertex of the above Given parabola = ( -0.2 ,  2.8 )
The Focus of the above Given parabola = ( -0.2 ,  2.85 )
The Directrix of the above Given parabola = -97

Example 2 :

Input :

Given first Term = 6
Given second Term = 3
Given Third Term = 1

Output:

The Vertex of the above Given parabola = ( -0.25 ,  0.625 )
The Focus of the above Given parabola = ( -0.25 ,  0.6666666666666666 )
The Directrix of the above Given parabola = -239

Program to Find Vertex, Focus and Directrix of Parabola

Below are the ways to find Vertex, Focus, and Directrix of Parabola.

Method #1: Using Mathematical Formula  (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Give the third number as static input and store it in another variable.
  • Print the vertex of the above-given parabola using Standard mathematical formulas.
  • Print the Focus of the above-given parabola using Standard mathematical formulas.
  • Print the Directrix of the above-given parabola using Standard mathematical formulas.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
vertx = 5
# Give the second number as static input and store it in another variable.
focs = 2
# Give the third number as static input and store it in another variable.
dirctx = 3
# Print the vertex of the above given parabola using Standard mathematical formulas.
print("The Vertex of the above Given parabola = (", (-focs / (2 * vertx)),
      ", ", (((4 * vertx * dirctx) - (focs * focs)) / (4 * vertx)), ")")
# Print the Focus of the above given parabola using Standard mathematical formulas.
print("The Focus of the above Given parabola = (", (-focs / (2 * vertx)), ", ",
      (((4 * vertx * dirctx) - (focs * focs) + 1) / (4 * vertx)), ")")
# Print the Directrix of the above given parabola using Standard mathematical formulas.
print("The Directrix of the above Given parabola =", (int)
      (dirctx - ((focs * focs) + 1) * 4 * vertx))

Output:

The Vertex of the above Given parabola = ( -0.2 ,  2.8 )
The Focus of the above Given parabola = ( -0.2 ,  2.85 )
The Directrix of the above Given parabola = -97

Method #2: Using Mathematical Formula  (User Input)

Approach:

  • Give the first number as User input using the input() function and store it in a variable.
  • Give the second number as User input using the input() function and store it in another variable.
  • Give the third number as User input using the input() function and store it in another variable.
  • Print the vertex of the above-given parabola using Standard mathematical formulas.
  • Print the Focus of the above-given parabola using Standard mathematical formulas.
  • Print the Directrix of the above-given parabola using Standard mathematical formulas.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as User input using the input() function  and store it in a variable.
vertx = int(input('Enter some Random Number = '))
# Give the second number as User input using the input() function  and store it in another variable.
focs =  int(input('Enter some Random Number = '))
# Give the third number as User input using the input() function  and store it in another variable.
dirctx =  int(input('Enter some Random Number = '))
# Print the vertex of the above given parabola using Standard mathematical formulas.
print("The Vertex of the above Given parabola = (", (-focs / (2 * vertx)),
      ", ", (((4 * vertx * dirctx) - (focs * focs)) / (4 * vertx)), ")")
# Print the Focus of the above given parabola using Standard mathematical formulas.
print("The Focus of the above Given parabola = (", (-focs / (2 * vertx)), ", ",
      (((4 * vertx * dirctx) - (focs * focs) + 1) / (4 * vertx)), ")")
# Print the Directrix of the above given parabola using Standard mathematical formulas.
print("The Directrix of the above Given parabola =", (int)
      (dirctx - ((focs * focs) + 1) * 4 * vertx))

Output:

Enter some Random Number = 6
Enter some Random Number = 3
Enter some Random Number = 1
The Vertex of the above Given parabola = ( -0.25 , 0.625 )
The Focus of the above Given parabola = ( -0.25 , 0.6666666666666666 )
The Directrix of the above Given parabola = -239

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.

Python Program to Find Super Factorial of a Number

Program to Find Super Factorial of a Number.

In the previous article, we have discussed Python Program to Calculate the Value of nPr
Super factorial :

Super factorial of a number is obtained by multiplying the first N factorials of a given Number.

Given a number, and the task is to find the superfactorial of an above-given number.

Examples:

Example1:

Input:

Given Number = 5

Output:

The super Factorial value of above given number =  34560

Example 2:

Input:

Given Number = 4

Output:

The super Factorial value of above given number =  288

Program to Find SuperFactorial of a Number.

Below are the ways to find the SuperFactorial of a given Number.

Method #1: Using For loop (Static Input)

Approach:

  • Import math module using the import keyword.
  • Give the number as static input and store it in a variable.
  • Take a variable and initialize its value with ‘1’.
  • Loop from ‘1 ‘ to the above-given number using For loop.
  • Calculate the factorial of the iterator value using the built-in factorial method and multiply it with the above-initialized superfactorial value.
  • Store it in another variable.
  • Print the superfactorial value of the above-given number.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the number as static input and store it in a variable.
gvn_numbr = 5
# Take a variable and initialize it's value with '1'.
supr_factrl = 1
# Loop from '1 ' to above given number using For loop.
for iteror in range(gvn_numbr+1):
  # Calculate the factorial of the iterator value using built-in factorial method
  # and multiply it with above initialized superfactorial value.
 # Store it in another variable.
    supr_factrl = supr_factrl * math.factorial(iteror)
# Print the superfactorial value of the above given number.
print("The super Factorial value of above given number = ", supr_factrl)

Output:

The super Factorial value of above given number =  34560

Method #2: Using For Loop (User input)

Approach:

  • Import math module using the import keyword.
  • Give the number as User input and store it in a variable.
  • Take a variable and initialize its value with ‘1’.
  • Loop from ‘1 ‘ to the above-given number using For loop.
  • Calculate the factorial of the iterator value using the built-in factorial method and multiply it with the above-initialized superfactorial value.
  • Store it in another variable.
  • Print the superfactorial value of the above-given number.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the number as User input and store it in a variable.
gvn_numbr = int(input("Enter some Random Number ="))
# Take a variable and initialize it's value with '1'.
supr_factrl = 1
# Loop from '1 ' to above given number using For loop.
for iteror in range(gvn_numbr+1):
  # Calculate the factorial of the iterator value using built-in factorial method
  # and multiply it with above initialized superfactorial value.
 # Store it in another variable.
    supr_factrl = supr_factrl * math.factorial(iteror)
# Print the superfactorial value of the above given number.
print("The super Factorial value of above given number = ", supr_factrl)

Output:

Enter some Random Number = 4
The super Factorial value of above given number = 288

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.

Python Program to Calculate the Value of nPr

Program to Calculate the Value of nPr

In the previous article, we have discussed Python Program to Find the Number of Weeks between two Dates
nPr:

nPr indicates n permutation r.

The process of organizing all the individuals in a given set to form a sequence is referred to as permutation.

The Given mathematical formula for nPr =n!/(n-r)!

Given the values of n, r and the task is to find the value of nPr.

Examples:

Example1:

Input:

Given n value = 5 
Given r value = 4

Output:

The value of nPr for above given n, r values =  120

Example 2:

Input:

Given n value = 6
Given r value = 3

Output:

The value of nPr for above given n, r values = 120

Program to Calculate the Value of nPr

Below are the ways to calculate the value of nPr for given values of n,r.

Method #1: Using math Module (Static Input)

Approach:

  • Import math module using the import keyword.
  • Give the number as static input and store it in a variable.
  • Give another number as static input and store it in another variable.
  • Calculate the value of nPr with reference to the standard mathematical formula n!/(n-r)! using factorial() function
  • Store it in a variable.
  • Print the value of nPr for the above-given n, r values.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the number as static input and store it in a variable.
gvn_n_val = 5
# Give another number as static input and store it in another variable.
gvn_r_val = 4
# Calculate the value of nPr with reference to standard mathematical formula n!/(n-r)!
# using factorial() function 
# Store it in a variable.
n_p_r = math.factorial(gvn_n_val)//math.factorial(gvn_n_val-gvn_r_val)
# Print the value of nPr for the above given n, r values.
print("The value of nPr for above given n, r values = ", n_p_r)

Output:

The value of nPr for above given n, r values =  120

Method #2: Using math Module (User input)

Approach:

  • Import math module using the import keyword.
  • Give the number as User input using the int(input()) function and store it in a variable.
  • Give another number as User input using the int(input()) function and store it in another variable.
  • Calculate the value of nPr with reference to the standard mathematical formula n!/(n-r)! using factorial() function
  • Store it in a variable.
  • Print the value of nPr for the above-given n, r values.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the number as user input using the int(input()) function and store it in a variable.
gvn_n_val = int(input("Enter some Random number = "))
# Give another number as user input using the int(input()) function and store it in another variable.
gvn_r_val = int(input("Enter some Random number = "))
# Calculate the value of nPr with reference to standard mathematical formula n!/(n-r)!
# using factorial() function 
# Store it in a variable.
n_p_r = math.factorial(gvn_n_val)//math.factorial(gvn_n_val-gvn_r_val)
# Print the value of nPr for the above given n, r values.
print("The value of nPr for above given n, r values = ", n_p_r)

Output:

Enter some Random number = 6
Enter some Random number = 3
The value of nPr for above given n, r values = 120

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.

Python Program to Check Buzz Number or Not

Program to Check Buzz Number or Not

In the previous article, we have discussed Python Program to Calculate the Area of a Trapezoid
Buzz Number:

If a number ends in 7 or is divisible by 7, it is referred to as a Buzz Number.

some of the examples of Buzz numbers are 14, 42, 97,107, 147, etc

The number 42 is a Buzz number because it is divisible by ‘7’.
Because it ends with a 7, the number 107 is a Buzz number.

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

Examples:

Example1:

Input:

Given number = 97

Output:

The given number { 97 } is a Buzz Number

Example2:

Input:

Given number = 120

Output:

The given number { 120 } is not a Buzz Number

Program to Check Buzz Number or Not

Below are the ways to check whether the given number is Buzz Number or not.

Method #1: Using modulus operator (Static input)

Approach:

  • Give the number as static input and store it in a variable.
  • Check if the given number modulus ‘7’ is equal to ‘0’ or if the given number modulus ’10’ is equal to ‘7’ or not using if conditional statement.
  • If the above statement is True, then print “The given number is a Buzz Number”.
  • Else if the statement is False, print “The given number is Not a Buzz Number”.
  • The Exit of the program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numbr = 14
# Check if the given number modulus '7' is equal to '0' or if the given number modulus '10'
# is  equal to '7' or not using if  conditional statement.
if gvn_numbr % 7 == 0 or gvn_numbr % 10 == 7:
 # If the above statement is True ,then print "The given number is a Buzz Number".
    print("The given number {", gvn_numbr, "} is a Buzz Number")
else:
  # Else if the statement is False, print "The given number is Not a Buzz Number" .
    print("The given number {", gvn_numbr, "} is not a Buzz Number")

Output:

The given number { 14 } is a Buzz Number

Here the number 14 is a Buzz Number.

Method #2: Using modulus operator (User input)

Approach:

  • Give the number as user input using int(input()) and store it in a variable.
  • Check if the given number modulus ‘7’ is equal to ‘0’ or if the given number modulus ’10’ is equal to ‘7’ or not using if conditional statement.
  • If the above statement is True, then print “The given number is a Buzz Number”.
  • Else if the statement is False, print “The given number is Not a Buzz Number”.
  • The Exit of the program.

Below is the implementation:

# Give the number as user input using int(input()) and store it in a variable.
gvn_numbr = int(input("Enter some random number = "))
# Check if the given number modulus '7' is equal to '0' or if the given number modulus '10'
# is  equal to '7' or not using if  conditional statement.
if gvn_numbr % 7 == 0 or gvn_numbr % 10 == 7:
 # If the above statement is True ,then print "The given number is a Buzz Number".
    print("The given number {", gvn_numbr, "} is a Buzz Number")
else:
  # Else if the statement is False, print "The given number is Not a Buzz Number" .
    print("The given number {", gvn_numbr, "} is not a Buzz Number")

Output:

Enter some random number = 49
The given number { 49 } is a Buzz Number

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.