Python Program to Find Strong Numbers in a List

Program to Find Strong Numbers in a List

In the previous article, we have discussed Python Program to Generate Strong Numbers in an Interval
Strong number:

A Strong number is a special number in which the total of all digit factorials equals the number itself.

Ex: 145 the sum of factorial of digits = 1 ! + 4 ! +5 ! = 1 + 24 +125

To determine whether a given number is strong or not. We take each digit from the supplied number and calculate its factorial, we will do this for each digit of the number.

We do the sum of factorials once we have the factorial of all digits. If the total equals the supplied number, the given number is strong; otherwise, it is not.

Given a list, and the task is to find all the Strong numbers in a given list.

Examples:

Example1:

Input:

Given List = [4, 1, 4, 145]

Output:

The Strong Numbers in a given List are :
1 145

Example2:

Input:

Given List =[5, 10, 650, 40585, 2, 145, 900]

Output:

The Strong Numbers in a given List are :
40585 2 145

Program to Find Strong Numbers in a List

Below are the ways to find all the Strong numbers in a given list.

Method #1: Using While loop and factorial() function (Static input)

Approach:

  1. Import the math module using the import keyword.
  2. Give the list as static input and store it in a variable.
  3. Loop in the above-given list using For Loop.
  4. Put the iterator value in a temporary variable called tempNum.
  5. Set a variable, say totalSum to zero. This will save the factorial sum of each of N’s digits.
  6. The number’s final digit must be saved in a variable, such as last_Digit = N % 10.
  7. Calculate the factorial of the last_Digit using math.factorial() function
  8. When the factorial of the last digit is found, it should be added to the totalSum = totalSumfactNum
  9. Following each factorial operation, the number must be reduced in terms of units by dividing it by ten that is  Itr = Itr /10
  10. Steps 5–8 should be repeated until N > 0.
  11. Check if the totalSum is equal to tempNum using the if conditional statement.
  12. If it is true then print the tempNum(which is the iterator value).
  13. The Exit of the program.

Below is the implementation:

# Import the math module using import keyword.
import math
# Give the list as static input and store it in a variable.
list1 = [4, 1, 4, 145]
# Loop in the above given list using For Loop.
print("The Strong Numbers in a given List are :")
for i in list1:
   # Taking a variable totalSum and initializing it with 0
    totalSum = 0
    # Put the iterator value in a temporary variable called tempNum.
    tempNum = i
    # using while to extract digit by digit of the given iterator value
    while(i):
        s = 1
        factNum = 1
        # Getting the last digit of the iterator value
        remainder = i % 10
        # calculating the factorial of the digit(extracted by remainder variable)
        # using math.fatorial function
        factNum = math.factorial(remainder)
        # Adding the factorial to the totalSum
        totalSum = totalSum + factNum
        # Dividing the given itertor value by 10
        i = i//10
    # checking if the totalSum is equal to the iterator value
    # if it is true then it is strong number then return true
    if(totalSum == tempNum):
        print(tempNum, end=' ')

Output:

The Strong Numbers in a given List are :
1 145

Method #2: Using While loop and factorial() function (User input)

Approach:

  1. Import the math module using the import keyword.
  2. Give the list as user input using list(),map(),input(),and split() functions and Store it in a variable.
  3. Loop in the above-given list using For Loop.
  4. Put the iterator value in a temporary variable called tempNum.
  5. Set a variable, say totalSum to zero. This will save the factorial sum of each of N’s digits.
  6. The number’s final digit must be saved in a variable, such as last_Digit = N % 10.
  7. Calculate the factorial of the last_Digit using math.factorial() function
  8. When the factorial of the last digit is found, it should be added to the totalSum = totalSumfactNum
  9. Following each factorial operation, the number must be reduced in terms of units by dividing it by ten that is  Itr = Itr /10
  10. Steps 5–8 should be repeated until N > 0.
  11. Check if the totalSum is equal to tempNum using the if conditional statement.
  12. If it is true then print the tempNum(which is the iterator value).
  13. The Exit of the program.

Below is the implementation:

# Import the math module using import keyword.
import math
#Give the list as user input using list(),map(),input(),and split() functions and 
#Store it in a variable
list1 = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Loop in the above given list using For Loop.
print("The Strong Numbers in a given List are :")
for i in list1:
   # Taking a variable totalSum and initializing it with 0
    totalSum = 0
    # Put the iterator value in a temporary variable called tempNum.
    tempNum = i
    # using while to extract digit by digit of the given iterator value
    while(i):
        s = 1
        factNum = 1
        # Getting the last digit of the iterator value
        remainder = i % 10
        # calculating the factorial of the digit(extracted by remainder variable)
        # using math.fatorial function
        factNum = math.factorial(remainder)
        # Adding the factorial to the totalSum
        totalSum = totalSum + factNum
        # Dividing the given itertor value by 10
        i = i//10
    # checking if the totalSum is equal to the iterator value
    # if it is true then it is strong number then return true
    if(totalSum == tempNum):
        print(tempNum, end=' ')

Output:

Enter some random List Elements separated by spaces = 1 145 10 15 2
The Strong Numbers in a given List are :
1 145 2

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 Print all Disarium Numbers within Given range

Program to Print all Disarium Numbers within Given range

In the previous article, we have discussed Python Program to Get Tangent value Using math.tan()
Disarium Number:

A Disarium number is one in which the sum of each digit raised to the power of its respective position equals the original number.

like 135 , 89, etc.

Here 1^1 + 3^2 + 5^3 = 135 so it is disarium Number

Examples:

Example1:

Input:

Given lower limit range = 7
Given upper limit range = 180

Output:

The disarium numbers in the given range 7 and 180 are: 
7 8 9 89 135 175

Example 2:

Input:

Given lower limit range = 1
Given upper limit range = 250

Output:

The disarium numbers in the given range 1 and 250 are:
1 2 3 4 5 6 7 8 9 89 135 175

Program to Print all Disarium Numbers within Given range

Below are the ways to Print all Disarium Numbers within the given range.

Method #1: Using For Loop (Static input)

Approach:

  • Give the lower limit range as static input and store it in a variable.
  • Give the upper limit range as static input and store it in another variable.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop take a variable say ‘num’ and initialize its value to the iterator value.
  • Make a copy of the number so you can verify the outcome later.
  • Make a result variable (with a value of 0) and an iterator ( set to the size of the number)
  • Create a while loop to go digit by digit through the number.
  • On each iteration, multiply the result by a digit raised to the power of the iterator value.
  • On each traversal, increment the iterator.
  • Compare the result value to a copy of the original number.
  • Print if the given number is a disarium number.
  • The Exit of the program.

Below is the implementation:

# Give the lower limit range as static input and store it in a variable.
lowlim_range = 7
# Give the upper limit range as static input and store it in another variable.
upplim_range = 180
print('The disarium numbers in the given range',
      lowlim_range, 'and', upplim_range, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for m in range(lowlim_range, upplim_range+1):

    # given number
    num = m
    # intialize result to zero(ans)
    ans = 0

    # calculating the digits
    digit_s = len(str(num))
    # copy the number in another variable(duplicate)
    dup_numbr = num
    while (dup_numbr != 0):
        # getting the last digit
        remaindr = dup_numbr % 10
        # multiply the result by a digit raised to the power of the iterator value.
        ans = ans + remaindr**digit_s
        digit_s = digit_s - 1
        dup_numbr = dup_numbr//10
    # It is disarium number if it is equal to original number
    if(num == ans):
        print(num, end=' ')

Output:

The disarium numbers in the given range 7 and 180 are:
7 8 9 89 135 175

Method #2: Using For Loop (User input)

Approach:

  • Give the lower limit range as user input using the int(input()) function and store it in a variable.
  • Give the upper limit range as user input using the int(input()) function and store it in another variable.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop take a variable say ‘num’ and initialize it’s value to  iterator value .
  • Make a copy of the number so you can verify the outcome later.
  • Make a result variable (with a value of 0) and an iterator ( set to the size of the number)
  • Create a while loop to go digit by digit through the number.
  • On each iteration, multiply the result by a digit raised to the power of the iterator value.
  • On each traversal, increment the iterator.
  • Compare the result value to a copy of the original number.
  • Print if the given number is a disarium number.
  • The Exit of the program.

Below is the implementation:

# Give the lower limit range as user input using the int(input()) function and store it in a variable.
lowlim_range = int(input("Enter some Random number = "))
# Give the upper limit range as user input using the int(input()) function and store it in another variable.
upplim_range = int(input("Enter some Random number = "))
print('The disarium numbers in the given range',
      lowlim_range, 'and', upplim_range, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for m in range(lowlim_range, upplim_range+1):

    # given number
    num = m
    # intialize result to zero(ans)
    ans = 0

    # calculating the digits
    digit_s = len(str(num))
    # copy the number in another variable(duplicate)
    dup_numbr = num
    while (dup_numbr != 0):
        # getting the last digit
        remaindr = dup_numbr % 10
        # multiply the result by a digit raised to the power of the iterator value.
        ans = ans + remaindr**digit_s
        digit_s = digit_s - 1
        dup_numbr = dup_numbr//10
    # It is disarium number if it is equal to original number
    if(num == ans):
        print(num, end=' ')

Output:

Enter some Random number = 1
Enter some Random number = 250
The disarium numbers in the given range 1 and 250 are:
1 2 3 4 5 6 7 8 9 89 135 175

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 Print Even Number Pattern

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Given the number of rows, the task is to print Even Number Pattern in C, C++, and Python.

Examples:

Example1:

Input:

Given number of rows = 10

Output:

20 
20 18 
20 18 16 
20 18 16 14 
20 18 16 14 12 
20 18 16 14 12 10 
20 18 16 14 12 10 8 
20 18 16 14 12 10 8 6 
20 18 16 14 12 10 8 6 4 
20 18 16 14 12 10 8 6 4 2

Example2:

Input:

Given number of rows = 6

Output:

12 
12 10 
12 10 8 
12 10 8 6 
12 10 8 6 4 
12 10 8 6 4 2

Program to Print Even Number Pattern in C, C++, and Python

Below are the ways to print Even Number Pattern in C, C++, and Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Take a variable and initialize it with 2*double the number of rows say lastnumb.
  • Take another variable and initialize it with the lastnumb say evennumb.
  • Loop from 1 to the number of rows using For loop.
  • Initialize the evennumb with the lastnumb.
  • Loop from 0 to the iterator value of the parent For loop using another for loop(Nested For loop).
  • Print the evennumb.
  • Reduce the evennumb by 2.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows as static input and store it in a variable.
numberOfRows = 10
# Take a variable and initialize it with 2*double the number of rows say lastnumb.
lastnumb = 2*numberOfRows
# Take another variable and initialize it with the lastnumb say evennumb.
evennumb = lastnumb
# Loop from 1 to the number of rows using For loop.
for m in range(1, numberOfRows+1):
    # Initialize the evennumb with the lastnumb.
    evennumb = lastnumb
    # Loop from 0 to the iterator value of the parent For loop using
    # another for loop(Nested For loop).
    for n in range(0, m):
        # Print the evennumb.
        print(evennumb, end=' ')
        # Reduce the evennumb by 2.
        evennumb = evennumb-2

    # Print the Newline character after the end of the inner loop.
    print()

Output:

20 
20 18 
20 18 16 
20 18 16 14 
20 18 16 14 12 
20 18 16 14 12 10 
20 18 16 14 12 10 8 
20 18 16 14 12 10 8 6 
20 18 16 14 12 10 8 6 4 
20 18 16 14 12 10 8 6 4 2

2) C++ Implementation

Below is the implementation:

#include <iostream>
#include <math.h>
using namespace std;
int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numberOfRows = 8;
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            cout << evennumb << " ";

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

16 
16 14 
16 14 12 
16 14 12 10 
16 14 12 10 8 
16 14 12 10 8 6 
16 14 12 10 8 6 4 
16 14 12 10 8 6 4 2

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numberOfRows = 8;
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            printf("%d ", evennumb);

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

16 
16 14 
16 14 12 
16 14 12 10 
16 14 12 10 8 
16 14 12 10 8 6 
16 14 12 10 8 6 4 
16 14 12 10 8 6 4 2

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows as user input and store it in a variable.
  • Take a variable and initialize it with 2*double the number of rows say lastnumb.
  • Take another variable and initialize it with the lastnumb say evennumb.
  • Loop from 1 to the number of rows using For loop.
  • Initialize the evennumb with the lastnumb.
  • Loop from 0 to the iterator value of the parent For loop using another for loop(Nested For loop).
  • Print the evennumb.
  • Reduce the evennumb by 2.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Give the number of rows as user input using int(input()) and store it in a variable.

Below is the implementation:

# Give the number of rows as user input using int(input()) and store it in a variable.
numberOfRows = int(input('Enter some random number of rows = '))
# Take a variable and initialize it with 2*double the number of rows say lastnumb.
lastnumb = 2*numberOfRows
# Take another variable and initialize it with the lastnumb say evennumb.
evennumb = lastnumb
# Loop from 1 to the number of rows using For loop.
for m in range(1, numberOfRows+1):
    # Initialize the evennumb with the lastnumb.
    evennumb = lastnumb
    # Loop from 0 to the iterator value of the parent For loop using
    # another for loop(Nested For loop).
    for n in range(0, m):
        # Print the evennumb.
        print(evennumb, end=' ')
        # Reduce the evennumb by 2.
        evennumb = evennumb-2

    # Print the Newline character after the end of the inner loop.
    print()

Output:

Enter some random number of rows = 10
20 
20 18 
20 18 16 
20 18 16 14 
20 18 16 14 12 
20 18 16 14 12 10 
20 18 16 14 12 10 8 
20 18 16 14 12 10 8 6 
20 18 16 14 12 10 8 6 4 
20 18 16 14 12 10 8 6 4 2

2) C++ Implementation

Give the number of rows as user input using cin and store it in a variable.

Below is the implementation:

#include <iostream>
using namespace std;
int main()
{

    // Give the number of rows as user input using
    // int(input()) and store it in a variable.
    int numberOfRows;
    cin >> numberOfRows;
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            cout << evennumb << " ";

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

6
12 
12 10 
12 10 8 
12 10 8 6 
12 10 8 6 4 
12 10 8 6 4 2 

3) C Implementation

Give the number of rows as user input using scanf and store it in a variable.

Below is the implementation:

#include <stdio.h>
int main()
{

    // Give the number of rows as user input using scanf and
    // store it in a variable.
    int numberOfRows;
    scanf("%d", &numberOfRows);
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            printf("%d ", evennumb);

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

6
12 
12 10 
12 10 8 
12 10 8 6 
12 10 8 6 4 
12 10 8 6 4 2

Related Programs:

Python Program to Check Sunny Number

Program to Check Sunny Number

In the previous article, we have discussed Python Program to Find the Missing Term of any Arithmetic Progression
Sunny Number:

A number is said to be a sunny number if the number next to it is a perfect square. In other words, if N+1 is a perfect square, then N is a sunny number.

Example :

Let Given number(N) = 3

Then N+1= 3+1 = 4 # which is a perfect square.

Therefore ,the Given number “3” is a Sunny Number.

some of the examples are 3,8 ,15, 24, 35 ,48 ,63, 80 ,99, 120 etc.

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

Examples:

Example1:

Input:

Given number = 3

Output:

The given number{ 3 } is Sunny Number

Example2:

Input:

Given number = 122

Output:

The given number{ 122 } is not a Sunny Number

Program to Check Sunny Number

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

Method #1: Using math.sqrt() function (Static input)

Approach:

  1. Import the math module using the import keyword.
  2. Give the number as static input and store it in a variable.
  3. Add ‘1’ to the above-given number and store it in another variable say “incremented number”.
  4. Calculate the Square root of the above-obtained number using math.sqrt() built-in function and store it in another variable.
  5. Multiply the above obtained Square root value with itself and store it in another variable say “square_number”.
  6. Check if the value of “square_number ” is equal to the “incremented number” using if conditional statement.
  7. If the statement is True,Print “The given number is Strong Number
  8. Else if the statement is False, print “The given number is Not a Strong Number”.
  9. The Exit of the program.

Below is the implementation:

# Import the math module using import keyword.
import math
# Give the number as static input and store it in a variable.
numb = 3
# Add '1' to the above given number and store it in another variable say
# "incremented number".
incremnt_num = numb + 1
# Calculate the Square root of the above obtained number using math.sqrt()
# built-in function and store it in another variable.
sqrt_numb = math.sqrt(incremnt_num)
# Multiply the above obtained Square root value with itself and
# store it in another variable say "square_number".
square_number = sqrt_numb * sqrt_numb
# Check if the value of "square_number " is equal the "incremented number"
# using if conditional statement.
if(square_number == incremnt_num):
  # If the statement is True ,Print "The given number is Strong Number"
    print("The given number{", numb, "} is Sunny Number")
else:
  # Else if the statement is False, print "The given number is Not a Strong Number" .
    print("The given number{", numb, "} is not a Sunny Number")

Output:

The given number{ 3 } is Sunny Number

Method #2: Using math.sqrt() function (User input)

Approach:

  1. Import the math module using the import keyword.
  2. Give the number as user input using the int(input()) function and store it in a variable.
  3. Add ‘1’ to the above-given number and store it in another variable say “incremented number”.
  4. Calculate the Square root of the above-obtained number using math.sqrt() built-in function and store it in another variable.
  5. Multiply the above obtained Square root value with itself and store it in another variable say “square_number”.
  6. Check if the value of “square_number ” is equal to the “incremented number” using if conditional statement.
  7. If the statement is True, Print “The given number is Strong Number”
  8. Else if the statement is False, print “The given number is Not a Strong Number”.
  9. The Exit of the program.

Below is the implementation:

# Import the math module using import keyword.
import math
# Give the number as user input using int(input()) and store it in a variable.
numb = int(input("Enter some random number = "))
# Add '1' to the above given number and store it in another variable say
# "incremented number".
incremnt_num = numb + 1
# Calculate the Square root of the above obtained number using math.sqrt()
# built-in function and store it in another variable.
sqrt_numb = math.sqrt(incremnt_num)
# Multiply the above obtained Square root value with itself and
# store it in another variable say "square_number".
square_number = sqrt_numb * sqrt_numb
# Check if the value of "square_number " is equal the "incremented number"
# using if conditional statement.
if(square_number == incremnt_num):
  # If the statement is True ,Print "The given number is Strong Number"
    print("The given number{", numb, "} is Sunny Number")
else:
  # Else if the statement is False, print "The given number is Not a Strong Number" .
    print("The given number{", numb, "} is not a Sunny Number")

Output:

Enter some random number = 30
The given number{ 30 } is not a Sunny 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.

 

Pandas: Create Dataframe from List of Dictionaries

Methods of creating a dataframe from a list of dictionaries

In this article, we discuss different methods by which we can create a dataframe from a list of dictionaries. Before going to the actual article let us done some observations that help to understand the concept easily. Suppose we have a list of dictionary:-

list_of_dict = [
{'Name': 'Mayank' , 'Age': 25, 'Marks': 91},
{'Name': 'Raj', 'Age': 21, 'Marks': 97},
{'Name': 'Rahul', 'Age': 23, 'Marks': 79},
{'Name': 'Manish' , 'Age': 23},
]

Here we know that dictionaries consist of key-value pairs. So we can analyze that if we make the key as our column name and values as the column value then a dataframe is easily created. And we have a list of dictionaries so a dataframe with multiple rows also.

pandas.DataFrame

This methods helps us to create dataframe in python

syntax: pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

Let us see different methods to create dataframe from a list of dictionaries

  • Method 1-Create Dataframe from list of dictionaries with default indexes

As we see in in pandas.Datframe() method there is parameter name data.We have to simply pass our list of dictionaries in this method and it will return the dataframe.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict)
print(df)

Output

   Age  Marks    Name
0   25     91  Mayank
1   21     97     Raj
2   23     79   Rahul
3   23     86  Manish

Here we see that dataframe is created with default indexes 0,1,2,3….

Now a question may arise if from any dictionary key-value pair is less than other dictionaries.So in this case what happened.Let understand it with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23},
]
#create dataframe
df=pd.DataFrame(list_of_dict)
print(df)

Output

    Age  Marks    Name
0  25.0   91.0  Mayank
1  21.0   97.0     Raj
2   NaN   79.0   Rahul
3  23.0    NaN  Manish

Here we see in case of missing key value pair NaN value is there in the output.

  • Method 2- Create Dataframe from list of dictionary with custom indexes

Unlike the previous method where we have default indexes we can also give custom indexes by passes list of indexes in index parameter of pandas.DataFrame() function.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23},
]
#create dataframe
df=pd.DataFrame(list_of_dict,index=['a','b','c','d'])
print(df)

Output

    Age  Marks    Name
a  25.0   91.0  Mayank
b  21.0   97.0     Raj
c   NaN   79.0   Rahul
d  23.0    NaN  Manish

Here we see that instead of default index 1,2,3….. we have now indes a,b,c,d.

  • Method 3-Create Dataframe from list of dictionaries with changed order of columns

With the help of pandas.DataFrame() method we can easily arrange order of column by simply passes list ozf columns in columns parameter in the order in which we want to display it in our dataframe.Let see this with the help of example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict,columns=['Name', 'Marks', 'Age'])
print(df)

Output

     Name  Marks  Age
0  Mayank     91   25
1     Raj     97   21
2   Rahul     79   23
3  Manish     86   23

Here also a question may arise if we pass less column in columns parameter or we pass more column in parameter then what happened.Let see this with the help of an example.

Case 1: Less column in column parameter

In this case the column which we don’t pass will be drop from the dataframe.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict,columns=['Name', 'Marks'])
print(df)

Output

     Name  Marks
0  Mayank     91
1     Raj     97
2   Rahul     79
3  Manish     86

Here we see that we didn’t pass Age column that’s why Age clumn is also not in our dataframe.

Case 2: More column in column parameter

In this case a new column will be added in dataframe but its all the value will be NaN.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict,columns=['Name', 'Marks', 'Age','city'])
print(df)

Output

     Name  Marks  Age  city
0  Mayank     91   25   NaN
1     Raj     97   21   NaN
2   Rahul     79   23   NaN
3  Manish     86   23   NaN

So these are the methods to create dataframe from list of dictionary in pandas.

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

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

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

numpy.full() :

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

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

Where,

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

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

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

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

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

Let’s see the below the program.

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

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

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

Let’s see the below the program.

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

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

Here initialized value is 1.

Let’s see the below the program.

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

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

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

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

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

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

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