Python

Pandas skip rows while reading csv file to a Dataframe using read_csv() in Python

Pandas: skip rows while reading csv file to a Dataframe using read_csv() in Python

In this tutorial, we will discuss how to skip rows while reading a csv file to a Dataframe using aread_csv()method of Pandas library in Python. If you want you can learn more about the read_csv() method along with syntax, parameters, and various methods to skip rows while reading specific rows from csv in python pandas

How to skip rows while reading CSV file using Pandas?

Python is a very useful language in today’s time, its also very useful for data analysis because of the different python packages. Python panda’s library implements a function to read a csv file and load data to dataframe quickly and also skip specified lines from csv file. Here we will use theread_csv()method of Pandas to skip n rows. i.e.,

pandas.read_csv(filepath_or_buffer, skiprows=N, ....)

Parameters:

ParameterUse
filepath_or_bufferURL or Dir location of file
sepStands for separator, default is ‘, ‘ as in csv(comma separated values)
index_colThis parameter is used to make the passed column as index instead of 0, 1, 2, 3…r
headerThis parameter is use to make passed row/s[int/int list] as header
use_colsThis parameter is only used the passed col[string list] to make a data frame
squeezeIf True and only one column is passed then returns pandas series
skiprowsThis parameter is used to skip passed rows in a new data frame
skipfooterThis parameter is used to skip the Number of lines at bottom of the file

Let’s, import the pandas’ module in python first:

Import pandas as pd

Let’s see the examples mentioned below and learn the process of Pandas: skip rows while reading csv file to a Dataframe using read_csv() in Python. Now, create one simple CSV file instru.csv

Name,Age,City
Tara,34,Agra
Rekha,31,Delhi
Aavi,16,Varanasi
Sarita,32,Lucknow
Mira,33,Punjab
Suri,35,Patna

Also Check:

Let’s load this csv file to a dataframe using read_csv() and skip rows in various ways,

Method 1: Skipping N rows from the starting while reading a csv file

When we pass skiprows=2 it means it will skip those rows while reading csv file. For example, if we want to skip 2 lines from the top while readingusers.csvfile and initializing a dataframe.

import pandas as pd
# Skip 2 rows from top in csv and initialize a dataframe
usersDf = pd.read_csv("C:\\Users\HP\Desktop\instru.csv", skiprows=2)
print('Contents of the Dataframe created by skipping top 2 lines from csv file ')
print(usersDf)

Skipping N rows from the starting while reading a csv file

Output:

Contents of the Dataframe created by skipping top 2 lines from csv file
  Rekha 31 Delhi
0 Aavi   16 Varanasi
1 Sarita 32 Lucknow
2 Mira   33 Punjab
3 Suri    35 Patna

Method 2: Skipping rows at specific index positions while reading a csv file to Dataframe

For skipping rows at specific index positions we have to give index positions like if we want to skip lines at index 0, 2, and 5 in dataframe ‘skiprows=[0,2,5]’.

import pandas as pd

# Skip  rows at specific index
usersDf = pd.read_csv("C:\\Users\HP\Desktop\instru.csv", skiprows=[0,2,5])
print('Contents of the Dataframe created by skipping specifying lines from csv file ')
print(usersDf)

Output:

Contents of the Dataframe created by skipping specifying lines from csv file
   Tara    34    Agra
0 Aavi   16     Varanasi
1 Sarita 32    Lucknow
2 Suri    35    Patna

It skipped all the lines at index positions 0, 2 & 5 from csv and loaded the remaining rows from csv.

Skipping N rows from top except header while reading a csv file to Dataframe

In the earlier example, we have seen that it removes the header also. In this, we want to remove 2 rows from starting but not the header one.

import pandas as pd
# Skip 2 rows from top except header
usersDf = pd.read_csv("C:\\Users\HP\Desktop\instru.csv", skiprows=[i for i in range(1,3)])
print('Contents of the Dataframe created by skipping 2 rows after header row from csv file ')
print(usersDf)

Output:

Contents of the Dataframe created by skipping 2 rows after header row from csv file
     Name Age City
0   Aavi    16   Varanasi
1  Sarita   32   Lucknow
2  Mira     33   Punjab
3  Suri      35   Patna

Skip rows from based on condition while reading a csv file to Dataframe

Here we will give some specific conditions using the lambda function for skipping rows in the dataframe.

Skip rows from based on condition while reading a csv file to Dataframe

import pandas as pd

def logic(index):
    if index % 3 == 0:
       return True
    return False
# Skip rows from based on condition like skip every 3rd line
usersDf = pd.read_csv("C:\\Users\HP\Desktop\instru.csv", skiprows= lambda x: logic(x) )
print('Contents of the Dataframe created by skipping every 3rd row from csv file ')
print(usersDf)

Output:

Contents of the Dataframe created by skipping every 3rd row from csv file
      Tara    34 Agra
0    Rekha 31 Delhi
1    Sarita 32 Lucknow
2    Mira   33 Punjab

Skip N rows from bottom/footer while reading a csv file to Dataframe

So here we use skipfooter & engine argument in pd.read_csv() to skip n rows from the bottom.

import pandas as pd

# Skip 2 rows from bottom
usersDf = pd.read_csv("C:\\Users\HP\Desktop\instru.csv", skipfooter=2, engine='python')
print('Contents of the Dataframe created by skipping bottom 2 rows from csv file ')
print(usersDf)

Output:

Contents of the Dataframe created by skipping bottom 2 rows from csv file
   Name Age City
0 Tara    34 Agra
1 Rekha 31 Delhi
2 Aavi    16 Varanasi
3 Sarita  32 Lucknow

Conclusion

In this article, you have learned different ways of how to skip rows while reading csv file to a Dataframe using the Python pandas read_csv() function.

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.

Similar Tutorials:

Pandas: skip rows while reading csv file to a Dataframe using read_csv() in Python Read More »

How to get first key in Dictionary – Python

How to get first key in Dictionary – Python | Get the First Key in Python Dictionary

How to get First Key in a Dictionary Python: In this tutorial, we will discuss different ways to get the first key in a dictionary. Later, we will see & learn how to choose the first N Keys of a dictionary in Python.

Get the first key from a dictionary using keys() method

Dictionary stores elements in key-value pairs.Dictionary act as a container in python. Dictionary provided keys() function which we will use to fetch all keys in it and after that we select the first key from a sequence.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first key in a dictionary
first_key = list(word_freq.keys())[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

In the above example, you can see that first we have fetched all dictionary elements and by using indexing we find out the first key value.

Do Refer:

Here is another way to do the same,

Another Way for How to get First Key in Dictionary Python

By using this method, it will convert all keys of the dictionary to a list and then we can select the first element from the list.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first ket in a dictionary
first_key = list(word_freq)[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

In the above example, we didn’t call the keys() function. We created a list of keys from the dictionary and selected the first item from it.

Get first key in a dictionary using iter() & next()

What we have done above that was not a perfect solution because first, we created a list and then fetch the first key in a dictionary. It is very difficult to apply that method in a large number of dictionaries. First, we iterate the object of keys using the iter() function then we apply the next() function on it for getting the first element.

Get first key in a dictionary using iter() & next()

This is an efficient solution because didn’t iterate over all the keys in a dictionary, we just selected the first one.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first key in a dictionary
first_key = next(iter(word_freq))
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Get the First Key in Dictionary Using list() Function

Also, there is a possible way to convert the dict type into a list using thelist() function at first and later get the first key at the 0th index of the dictionary.

my_dict = { 'Russia': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

print(list(my_dict.keys())[0])

Result:

Russia

Get the First Key in Dictionary Using for Loop

One more easiest way to get the initial key in a dictionary is using theforloop. After getting the first key of the dictionary break the loop.

Let’s see an example on it:

my_dict = { 'London': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

for key, value in my_dict.items():
  print(key)
  break

Output:

London

Get first N keys from a Dictionary in Python

To select the first N keys from a dictionary, convert the keys of a dictionary to a list and then select the first N entries from that. For example, let’s see how to select the first 3 keys from a dictionary,

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first ket in a dictionary
first_key = list(word_freq)[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Conclusion on Get First value in a dictionary of string and int

In this article, we have seen discuss different ways to find out the first key of a dictionary in python. All these dictionary keys methods in python help to find easily the key value in a dictionary of string and int word_freq. Get first key of the dictionary in python information completely from this article.

How to get first key in Dictionary – Python | Get the First Key in Python Dictionary Read More »

How to save Numpy Array to a CSV File using numpy.savetxt() in Python

How to save Numpy Array to a CSV File using numpy.savetxt() in Python? | Savetxt Function’s Working in Numpy with Examples

NumPy arrays are very essential data structures for working with data in Python, machine learning models. Python’s Numpy module provides a function to save a numpy array to a txt file with custom delimiters and other custom options. In this tutorial, we will discuss the procedure of how to save Numpy Array to a CSV File with clear steps.

numpy.savetxt() Function

The numpy.savetxt() function is the counterpart of the NumPy loadtxt() function and can save arrays in delimited file formats such as CSV. Save the array we created with the following function call:

Synatx : numpy.savetxt(fname, array_name, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)

Where,

  • fname: If the filename ends in .gz, the file is automatically saved in compressed gzip format. The loadtxt() function can understand gzipped files transparently.
  • arr_name: It indicates data to be saved like 1D or 2D numpy array.
  • fmt: It refers to a formatting pattern or sequence of patterns, which will be used while saving elements to file.
  • delimiter: It is optional, refers to string or character to be used as element separator
  • newline: It is optional, refers to string or character to be used as line separator
  • header: It refers to a string that is written at the beginning of the file.
  • footer: It refers to a string that to be written at the end of the txt file.
  • comments: It refers to a custom comment marker, where the default is ‘#’. It will be pre-appended to the header and footer.

How to save Numpy Array to a CSV File using numpy.savetxt() in Python?

One of the most common file formats for storing numerical data in files is the comma-separated variable format or CSV in Short. Usually, input data are stored in CSV Files as it is one of the most convenient ways for storing data.

Savetxt function is used to save Numpy Arrays as CSV Files. The function needs a filename and array as arguments to save an array to CSV File. In addition, you need to mention the delimiter; for separating each variable in the file or most commonly comma. You can set via the “delimiter” argument.

Example Program on How to Save a Numpy Array to a CSV File

#Program :

import numpy as np
def main():
   # Numpy array created with a list of numbers
   array1D = np.array([9, 1, 23, 4, 54, 7, 8, 2, 11, 34, 42, 3])
   print('Real Array : ', array1D)
   print('<** Saved 1D Numpy array to csv file **>')
   # Save Numpy array to csv
   np.savetxt('array.csv', [array1D], delimiter=',', fmt='%d')
   print('*** Saving 1D Numpy array to csv file with Header and Footer ***')
   # Saving Numpy array to csv with custom header and footer
   np.savetxt('array_hf.csv', [array1D], delimiter=',', fmt='%d' , header='A Sample 2D Numpy Array :: Header', footer='This is footer')

   print('*** Saving 2D Numpy array to csv file ***')
   # A 2D Numpy array list of list created
   array2D = np.array([[111, 11, 45, 22], [121, 22, 34, 14], [131, 33, 23, 7]])
   print('2D Numpy Array')
   print(array2D)
   # Saving 2D numpy array to csv file
   np.savetxt('2darray.csv', array2D, delimiter=',', fmt='%d')
   # Saving 2nd column of 2D numpy array to csv file
   np.savetxt('2darray_column.csv', [array2D[:,1]], delimiter=',', fmt='%d')
   # Saving 2nd row of 2D numpy array to csv file
   np.savetxt('2darray_row.csv', [array2D[1] ], delimiter=',', fmt='%d')

   # Creating the type of a structure
   dtype = [('Name', (np.str_, 10)), ('Marks', np.float64), ('GradeLevel', np.int32)]
   #Creating a Strucured Numpy array
   structuredArr = np.array([('Sam', 33.3, 3), ('Mike', 44.4, 5), ('Aadi', 66.6, 6), ('Riti', 88.8, 7)], dtype=dtype)
   print(structuredArr)
   # Saving 2D numpy array to csv file
   np.savetxt('struct_array.csv', structuredArr, delimiter=',', fmt=['%s' , '%f', '%d'], header='Name,Marks,Age', comments='')
if __name__ == '__main__':
  main()

Python Program for Saving Numpy Array to a CSV File

Output:

Real Array :  [ 9  1 23  4 54  7  8  2 11 34 42  3]
<** Saved 1D Numpy array to csv file **>
<** Saved 1D Numpy array to csv file with custom  Header and Footer **>
<** Save 2D Numpy array to csv file **>
* 2D Numpy Array *
[[111  11  45  22]
[121  22  34  14]
[131  33  23   7]]
[('Rags', 33.3, 3) ('Punit', 44.4, 5) ('Drishti', 66.6, 6)  ('Ritu', 88.8, 7)]

The Passed Delimeter ‘,’ will change to CSV Format. In addition, the format string %d passed will store the elements as integers. By default, it will store numbers in float format. Keep in mind that if you don’t mention [] around numpy array to change it to list while passing numpy.savetxt() comma delimiter willn’t work and uses ‘\n’ by default. Thus, surrounding array by [] i.e. [arr] is mandatory.

Save 1D Numpy array to CSV file with Header and Footer

In order to add comments to the header and footer while saving to a CSV File, we can pass the Header and Footer Parameters as such

# Save Numpy array to csv with custom header and footer
np.savetxt('array_hf.csv', [arr], delimiter=',', fmt='%d' , header='A Sample 2D Numpy Array :: Header', footer='This is footer')

Usually, By default comments in both the header and footer are pre-appended by ‘#’. To change this we can pass the parameter comments like comments=’@’.

Final Words

Numpy savetxt can be an extremely helpful method for saving an array to CSV File. If you want to manipulate or change the existing data set this can be a great method. If you have any queries don’t hesitate to ask us via comment box so that we can get back to you at the soonest possible. Bookmark our site for the latest updates on Python, Java, C++, and Other Programming Languages.

How to save Numpy Array to a CSV File using numpy.savetxt() in Python? | Savetxt Function’s Working in Numpy with Examples Read More »

Python Check if Two Lists are Equal

Python: Check if Two Lists are Equal | How do you Check if a List is the Same as Another List Python?

In Order to check if two lists or identical or not we need to check if two unordered lists have similar elements in the exact similar position.  You might need this in your day-to-day programming. Go through the tutorial over here and determine if two lists are equal or not in Python easily.

We have mentioned the various techniques for finding if a list is the same as the Another or Not along with sample programs. Use them as a guide for resolving your doubts if any on Comparing Two Lists and finding whether they are identical or not. You can also find difference between two lists python by going through our other tutorials.

List – Definition

Multiple items may be stored in a single variable using lists. Square brackets[] are used to create a list. Lists are one of four built-in Python storage types for storing sets of data; the other three are Tuple, Set, and Dictionary, all of which have different qualities and applications.

Examples for Checking if Two Lists are Equal or Not

Comparing lists irrespective of the order of lists:

Input:

firstlist = ['hello', 'this', 'is', 'BTechGeeks'] 

secondlist = ['this', 'is', 'BTechGeeks','hello']

Output:

Both lists are equal

Input:

firstlist = ['hello', 'this', 'is', 'BTechGeeks','is'] 

secondlist = ['this', 'is', 'BTechGeeks','hello','the']

Output:

Both lists are not equal

Comparing list based on the order of lists:

Input:

firstlist = ['this' ,'is','BTechGeeks']
secondlist = ['this' ,'is','BTechGeeks']

Output:

Both lists are equal

Input:

firstlist = ['hello', 'this' ,'is','BTechGeeks']
secondlist = ['this' ,'is','BTechGeeks']

Output:

Both lists are not equal

How to Compare if Two Lists are Identical or Not?

There are several ways to check if two lists are equal or not. We have outlined some of them so that you can choose the method that you are comfortable with and determine if the two lists are equal or not. They are explained in the following way

  • Using sorting()
  • Using Counter() function
  • Using np.array_equal()
  • Using ‘=’ Operator
  • Using reduce() +map()

Check lists irrespective of order of elements

Method #1: Using sorting()

We start by sorting the list so that if both lists are similar, the elements are in the same place. However, this ignores the order of the elements in the list. So, by comparing sorting versions of lists, we can determine whether or not they are equal.

Below is the implementation:

# function to check both lists if they are equal
def checkList(firstlist, secondlist):
    # sorting the lists
    firstlist.sort()
    secondlist.sort()
    # if both the lists are equal the print yes
    if(firstlist == secondlist):
        print("Both lists are equal")
    else:
        print("Both lists are not equal")


# Driver code
# given two lists
firstlist = ['hello', 'this', 'is', 'BTechGeeks']
secondlist = ['this', 'is', 'BTechGeeks','hello']
# passing both the lists to checklist function
checkList(firstlist, secondlist)

Python Program to check if two lists are equal or not using Sorting()

Output:

Both lists are not equal

Method #2: Using Counter() function

We can normally get the frequency of each variable in a list using Counter(), and we can search for it in both lists to see whether they are similar or not. However, this approach disregards the order of the elements in the list and only considers the frequency of the elements.

Below is the implementation:

# importing counter function from collections
from collections import Counter

# function to check both lists if they are equal
def checkList(firstlist, secondlist):
    # Getting frequencies of both lists
    firstfreq = Counter(firstlist)
    secondfreq = Counter(secondlist)
    # if both the lists are equal the print yes
    if(firstfreq == secondfreq):
        print("Both lists are equal")
    else:
        print("Both lists are not equal")


# Driver code
# given two lists
firstlist = ['hello', 'this', 'is', 'BTechGeeks'] 
secondlist = ['this', 'is', 'BTechGeeks','hello']
# passing both the lists to checklist function
checkList(firstlist, secondlist)

Comparison of two lists using counter() function in Python

Output:

Both lists are not equal

Method #3: Using np.array_equal()

From our lists, we can generate two sorted numpy arrays, which we can compare using numpy.array equal() to see if they contain the same elements.

Below is the implementation:

# importing numpy
import numpy
# function to check both lists if they are equal
def checkList(firstlist, secondlist):
    # Convert both lists to sorted numpy arrays and compare them to see if they're equal.
    if(numpy.array_equal(numpy.array(firstlist).sort(), numpy.array(secondlist).sort())):
        print("Both lists are equal")
    else:
        print("Both lists are not equal")


# Driver code
# given two lists
firstlist = ['hello', 'this', 'is', 'BTechGeeks'] 
secondlist = ['this', 'is', 'BTechGeeks','hello']
# passing both the lists to checklist function
checkList(firstlist, secondlist)

Output:

Both lists are not equal

Checking lists based on of order of elements

Method #4: Using ‘=’ Operator

The == operator can be used to compare two lists directly. If both lists are exactly identical, it will return True; otherwise, it will return False.

Below is the implementation:

# function to check if both the lists are same
def checkList(firstlist, secondlist):
    # if both the lists are equal the print yes
    if(firstlist == secondlist):
        print("Both lists are equal")
    else:
        print("Both lists are not equal")


# Driver code
# given two lists
firstlist = ['hello', 'this', 'is', 'BTechGeeks']
secondlist = ['hello', 'this', 'is', 'BTechGeeks']
# passing both the lists to checklist function
checkList(firstlist, secondlist)

Comparison of two lists using = Operator in Python

Output:

Both lists are not equal

Method #5: Using reduce() +map()

We can accomplish this task of checking for the equality of two lists by carefully coupling the power of map() to hash values and the utility of reduce(). This also takes into account the list’s order.

Below is the implementation:

# importing reduce from functools
from functools import reduce
# function to check if both the lists are same
def checkList(firstlist, secondlist):
    # if both the lists are equal the print yes
    if(reduce(lambda a, b: a and b, map(lambda x, y: x == y, firstlist, secondlist))):
        print("Both lists are equal")
    else:
        print("Both lists are not equal")


# Driver code
# given two lists
firstlist = ['hello', 'this', 'is', 'BTechGeeks']
secondlist = ['hello', 'this', 'is', 'BTechGeeks']
# passing both the lists to checklist function
checkList(firstlist, secondlist)

Output:

Both lists are not equal

Python: Check if Two Lists are Equal | How do you Check if a List is the Same as Another List Python? Read More »

Program to Replace a Word with Asterisks in a Sentence

Python Program to Replace a Word with Asterisks in a Sentence

In the previous article, we have discussed Python Program to Find Sum of Odd Factors of a Number
Given a sentence and the task is to replace a word with asterisks in a given Sentence.

Examples:

Example1:

Input:

Given string = "hello this is btechgeeks btechgeeks"
Given word to be replaced = "btechgeeks"

Output:

The given string [ hello this is btechgeeks btechgeeks ] after replacing with a given word with an asterisk :
hello this is ********** **********

Example2:

Input:

Given string = "good morning this is btechgeeks good morning all"
Given word to be replaced = "good"

Output:

The given string [ good morning this is btechgeeks good morning all ] after replacing with a given word with an asterisk :
**** morning this is btechgeeks **** morning all

Program to Replace a Word with Asterisks in a Sentence in Python

Below are the ways to replace a word with asterisks in a given Sentence:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Give the replaceable word as static input and store it in another variable.
  • Split the given string into a list of words using the split() function and store it in another variable say “wrd_lst”.
  • Multiply the asterisk symbol with the length of the given input word using the len() function and store it in another variable say “replaced_word”.
  • Loop in the above-obtained word list using the for loop.
  • Check if the word at the iterator index is equal is given input word using the if conditional statement.
  • If the statement is true, replace the word at the iterator index with the replaced_word.
  • Convert the above-got word list to string using the join() function.
  • Print the above-obtained string to replace a word with an asterisk in a given input sentence.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "hello this is btechgeeks btechgeeks"
# Give the replaceable word as static input and store it in another variable.
gvn_wrd = "btechgeeks"
# Split the given string into a list of words using the split() function and
# store it in another variable say "wrd_lst".
wrd_lst = gvn_str.split()
# Multiply the asterisk symbol with the length of the given input word using
# the len() function and store it in another variable.
replacd_word = '*' * len(gvn_wrd)
# Loop in the above-obtained word list using the for loop.
for itr in range(len(wrd_lst)):
  # Check if the iterator value is equal to the given input word using the if
  # conditional statement.
 # check if thw word at the iterator index is equal is given
    if wrd_lst[itr] == gvn_wrd:
      # if it is truw thwn replce the word t the iterator index with the replaced word
        wrd_lst[itr] = replacd_word
# Convert the above-got word list to string using the join() function.
finl_str = ' '.join(wrd_lst)
# Print the above-obtained string to replace a word with an asterisk in a
# given input sentence.
print("The given string [", gvn_str,
      "] after replacing with a given word with an asterisk :")
print(finl_str)

Output:

The given string [ hello this is btechgeeks btechgeeks ] after replacing with a given word with an asterisk :
hello this is ********** **********

Method #2: Using For loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Give the replaceable word as user input using the input() function and store it in another variable.
  • Split the given string into a list of words using the split() function and store it in another variable say “wrd_lst”.
  • Multiply the asterisk symbol with the length of the given input word using the len() function and store it in another variable say “replaced_word”.
  • Loop in the above-obtained word list using the for loop.
  • Check if the word at the iterator index is equal is given input word using the if conditional statement.
  • If the statement is true, replace the word at the iterator index with the replaced_word.
  • Convert the above-got word list to string using the join() function.
  • Print the above-obtained string to replace a word with an asterisk in a given input sentence.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random sentence = ")
# Give the replaceable word as user input using the input() function and store it in another variable.
gvn_wrd = input("Enter some random word = ")
# Split the given string into a list of words using the split() function and
# store it in another variable say "wrd_lst".
wrd_lst = gvn_str.split()
# Multiply the asterisk symbol with the length of the given input word using
# the len() function and store it in another variable.
replacd_word = '*' * len(gvn_wrd)
# Loop in the above-obtained word list using the for loop.
for itr in range(len(wrd_lst)):
  # Check if the iterator value is equal to the given input word using the if
  # conditional statement.
 # check if thw word at the iterator index is equal is given
    if wrd_lst[itr] == gvn_wrd:
      # if it is truw thwn replce the word t the iterator index with the replaced word
        wrd_lst[itr] = replacd_word
# Convert the above-got word list to string using the join() function.
finl_str = ' '.join(wrd_lst)
# Print the above-obtained string to replace a word with an asterisk in a
# given input sentence.
print("The given string [", gvn_str,
      "] after replacing with a given word with an asterisk :")
print(finl_str)

Output:

Enter some random sentence = good morning this is btechgeeks good morning all
Enter some random word = good
The given string [ good morning this is btechgeeks good morning all ] after replacing with a given word with an asterisk :
**** morning this is btechgeeks **** morning all

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 Replace a Word with Asterisks in a Sentence Read More »

Program to Sort Palindrome Words in a Sentence

Python Program to Sort Palindrome Words in a Sentence

In the previous article, we have discussed Python Program to Find the Sum of Digits of a Number at Even and Odd places
Given a string and the task is to sort all the palindrome words in a given sentence.

Palindrome:

If the reverse of the given string is the same as the given original string, it is said to be a palindrome.

Example :

Given string = “sos asked to bring the madam pip “.

Output :

Explanation: In this “madam”, “pip”, “sos” are the palindromic words. By sorting them we get {“madam”, ‘pip’ , “sos”}

Examples:

Example1:

Input:

Given string/sentence ='sos how are you madam pip instal'

Output:

The given string before sorting all the palindromic words is =  sos how are you madam pip instal
The final string after sorting all the palindromic words is =  madam how are you pip sos instal

Example2:

Input:

Given string/sentence = 'the good is madam aba dad mom din cac'

Output:

The given string before sorting all the palindromic words is = the good is madam aba dad mom din cac
The final string after sorting all the palindromic words is = the good is aba cac dad madam din mom

Program to Sort Palindrome Words in a Sentence in Python

Below are the ways to sort all the palindromic words in a given sentence:

Method #1: Using Sort() function (Static input)

Approach:

  • Give the sentence/string as static input and store it in a variable.
  • Convert the given sentence to a list of words using list() and split() functions and store it another variable.
  • Take an empty list to say palindromicwordslist that stores all the palindromic words in the given string and initialize it to null/empty using the list() function or [].
  • Traverse the given list of words using a for loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then append this word to the palindromicwordslist using the append() function.
  • Sort the palindromicwordslist using the sort() function.
  • Take a variable say tempo and initialize its value to 0(Here it acts as a pointer to palindromicwordslist ).
  • Traverse the list of words of the given sentence using the For loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then modify the word with the palindromicwordslist[tempo] word.
  • Increment the tempo value by 1.
  • Convert this list of words of the given sentence to the string using the join() function.
  • Print the final string after sorting the palindromic words.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as static input and store it in a variable.
gvnstrng = 'sos how are you madam pip instal'
# Convert the given sentence to a list of words using list()
# and split() functions and store it another variable.
strngwrdslst = list(gvnstrng.split())
# Take an empty list to say palindromicwordslist
# that stores all the palindromic words in the given string
# and initialize it to null/empty using the list() function or [].
palindromicwordslist = []
# Traverse the given list of words using a for loop.
for wrd in strngwrdslst:
        # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(wrd == wrd[::-1]):
        # If it is true then append this word to the palindromicwordslist
        # using the append() function.
        palindromicwordslist.append(wrd)

# Sort the palindromicwordslist using the sort() function.
palindromicwordslist.sort()
# Take a variable say tempo and initialize its value to 0
# (Here it acts as a pointer to palindromicwordslist ).
tempo = 0
# Traverse the list of words of the given sentence using the For loop.
for wrditr in range(len(strngwrdslst)):
  # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(strngwrdslst[wrditr] == strngwrdslst[wrditr][::-1]):
        # If it is true then modify the word with the palindromicwordslist[tempo] word.
        strngwrdslst[wrditr] = palindromicwordslist[tempo]
        tempo = tempo+1
        # Increment the tempo value by 1.


# Convert this list of words of the given sentence
# to the string using the join() function.
finalstrng = ' '.join(strngwrdslst)
print('The given string before sorting all the palindromic words is = ', gvnstrng)
# Print the final string after sorting the palindromic words.
print('The final string after sorting all the palindromic words is = ', finalstrng)

Output:

The given string before sorting all the palindromic words is =  sos how are you madam pip instal
The final string after sorting all the palindromic words is =  madam how are you pip sos instal

Method #2:Using Sort() function (User input)

Approach:

  • Give the sentence/string as user input using the input() function and store it in a variable.
  • Convert the given sentence to a list of words using list() and split() functions and store it another variable.
  • Take an empty list to say palindromicwordslist that stores all the palindromic words in the given string and initialize it to null/empty using the list() function or [].
  • Traverse the given list of words using a for loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then append this word to the palindromicwordslist using the append() function.
  • Sort the palindromicwordslist using the sort() function.
  • Take a variable say tempo and initialize its value to 0(Here it acts as a pointer to palindromicwordslist ).
  • Traverse the list of words of the given sentence using the For loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then modify the word with the palindromicwordslist[tempo] word.
  • Increment the tempo value by 1.
  • Convert this list of words of the given sentence to the string using the join() function.
  • Print the final string after sorting the palindromic words.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as user input using input() function
# and store it in a variable.
gvnstrng = input('Enter some random string = ')
# Convert the given sentence to a list of words using list()
# and split() functions and store it another variable.
strngwrdslst = list(gvnstrng.split())
# Take an empty list to say palindromicwordslist
# that stores all the palindromic words in the given string
# and initialize it to null/empty using the list() function or [].
palindromicwordslist = []
# Traverse the given list of words using a for loop.
for wrd in strngwrdslst:
        # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(wrd == wrd[::-1]):
        # If it is true then append this word to the palindromicwordslist
        # using the append() function.
        palindromicwordslist.append(wrd)

# Sort the palindromicwordslist using the sort() function.
palindromicwordslist.sort()
# Take a variable say tempo and initialize its value to 0
# (Here it acts as a pointer to palindromicwordslist ).
tempo = 0
# Traverse the list of words of the given sentence using the For loop.
for wrditr in range(len(strngwrdslst)):
  # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(strngwrdslst[wrditr] == strngwrdslst[wrditr][::-1]):
        # If it is true then modify the word with the palindromicwordslist[tempo] word.
        strngwrdslst[wrditr] = palindromicwordslist[tempo]
        tempo = tempo+1
        # Increment the tempo value by 1.


# Convert this list of words of the given sentence
# to the string using the join() function.
finalstrng = ' '.join(strngwrdslst)
print('The given string before sorting all the palindromic words is = ', gvnstrng)
# Print the final string after sorting the palindromic words.
print('The final string after sorting all the palindromic words is = ', finalstrng)

Output:

Enter some random string = the good is madam aba dad mom din cac
The given string before sorting all the palindromic words is = the good is madam aba dad mom din cac
The final string after sorting all the palindromic words is = the good is aba cac dad madam din mom

 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 Sort Palindrome Words in a Sentence Read More »

Pandas Drop Rows With NaNMissing Values in any or Selected Columns of Dataframe

Pandas: Drop Rows With NaN/Missing Values in any or Selected Columns of Dataframe

Pandas provide several data structures and operations to manipulate data and time series. There might be instances in which some data can go missing and pandas use two values to denote the missing data namely None, NaN. You will come across what does None and Nan indicate. In this tutorial we will discuss the dropna() function, why is it necessary to remove rows which contain missing values or NaN, and different methods to drop rows with NaN or Missing values in any or selected column in the dataframe.

dropna() function

The dropna() function is used to analyze and drop rows or columns having NaN or missing values in different ways.

syntax:  DataFrameName.dropna(axis, how, thresh, subset, inplace)

Parameters:

1) axis: If the axis is 0 rows with missing or NaN values will be dropped else if axis=1 columns with NaN or missing values will be dropped.

2) how: how to take a string as a parameter ‘any’ or ‘all’.  ‘any’ is used if any NaN value is present otherwise ‘all’ is used if all values are NaN.

3) thresh: It tells the minimum amount of NaN values that is to be dropped.

4) inplace: If inplace is true chance will be made in the existing dataset otherwise changes will be made in different datasets.

The Necessity to remove NaN or Missing values

NaN stands for Not a Number. It is used to signify whether a particular cell contains any data or not. When we work on different datasets we found that there are some cells that may have NaN or missing values. If we work on that type of dataset then the chances are high that we do not get an accurate result. Hence while working on any dataset we check whether our datasets contain any missing values or not. If it contains NaN values we will remove it so as to get results with more accuracy.

How to drop rows of Pandas DataFrame whose value in a certain column is NaN or a Missing Value?

There are different methods to drop rows of Pandas Dataframe whose value is missing or Nan. All 4 methods are explained with enough examples so that you can better understand the concept and apply the conceptual knowledge to other programs on your own.

Method 1: Drop Rows with missing value / NaN in any column

In this method, we will see how to drop rows with missing or NaN values in any column. As we know in all our methods dropna() function is going to be used hence we have to play with parameters. By default value of the axis is 0 and how is ‘any’ hence dropna() function without any parameter will going to be used to drop rows with missing or NaN values in any column. 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', np.NaN,'Rajasthan' , np.NaN) ,
            ('Ajjet', 21, 'Delhi' , 74)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age', 'City', 'Marks'])
print("Original Dataframe\n")
print(df,'\n')
new_df=df.dropna()
print("New Dataframe\n")
print(new_df)

How to Drop Rows with missing valueNaN in any column of Pandas Dataframe

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        NaN   81.0
3  Abhay   NaN  Rajasthan    NaN
4  Ajjet  21.0      Delhi   74.0 

New Dataframe

    Name   Age    City  Marks
0    Raj  24.0  Mumbai   95.0
1  Rahul  21.0   Delhi   97.0
4  Ajjet  21.0   Delhi   74.0

Here we see that we get only those rows that don’t have any NaN or missing value.

Method 2: Drop Rows in dataframe which has all values as NaN

In this method, we have to drop only those rows in which all the values are NaN or missing. Hence we have to only pass how as an argument with value ‘all’ and all the parameters work with their default values. Let see this with 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', np.NaN,'Rajasthan' , np.NaN) ,
            ('Ajjet', 21, 'Delhi' , 74),
            (np.NaN,np.NaN,np.NaN,np.NaN),
            ('Aman',np.NaN,np.NaN,76)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age', 'City', 'Marks'])
print("Original Dataframe\n")
print(df,'\n')
new_df=df.dropna(how='all')
print("New Dataframe\n")
print(new_df)

 

How to Drop Rows in dataframe which has all values as NaN in Pandas Dataframe

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        NaN   81.0
3  Abhay   NaN  Rajasthan    NaN
4  Ajjet  21.0      Delhi   74.0
5    NaN   NaN        NaN    NaN
6   Aman   NaN        NaN   76.0 

New Dataframe

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

Here we see that row 5 is dropped because it has all the values as NaN.

Method 3: Drop Rows with any missing value in selected columns only

In this method, we see how to drop rows with any of the NaN values in the selected column only. Here also axis and how to take default value but we have to give a list of columns in the subset in which we want to perform our operation. 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', np.NaN,'Rajasthan' , np.NaN) ,
            ('Ajjet', 21, 'Delhi' , 74),
            (np.NaN,np.NaN,np.NaN,np.NaN),
            ('Aman',np.NaN,np.NaN,76)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age', 'City', 'Marks'])
print("Original Dataframe\n")
print(df,'\n')
new_df=df.dropna(subset=['Name', 'Age'])
print("New Dataframe\n")
print(new_df)

How to Drop Rows with any missing value in selected columns only in Pandas Dataframe

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        NaN   81.0
3  Abhay   NaN  Rajasthan    NaN
4  Ajjet  21.0      Delhi   74.0
5    NaN   NaN        NaN    NaN
6   Aman   NaN        NaN   76.0 

New Dataframe

    Name   Age    City  Marks
0    Raj  24.0  Mumbai   95.0
1  Rahul  21.0   Delhi   97.0
2   Aadi  22.0     NaN   81.0
4  Ajjet  21.0   Delhi   74.0

Here we see in rows 3,5 and 6 columns ‘Name’ and ‘Age’ has NaN or missing values so these columns are dropped.

Method 4: Drop Rows with missing values or NaN in all the selected columns

In this method we see how to drop rows that have all the values as NaN or missing values in a select column i.e if we select two columns ‘A’ and ‘B’ then both columns must have missing values. Here we have to pass a list of columns in the subset and ‘all’ in how. 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', np.NaN,'Rajasthan' , np.NaN) ,
            ('Ajjet', 21, 'Delhi' , 74),
            (np.NaN,np.NaN,np.NaN,np.NaN),
            ('Aman',np.NaN,np.NaN,76)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age', 'City', 'Marks'])
print("Original Dataframe\n")
print(df,'\n')
new_df=df.dropna(how='all',subset=['Name', 'Age'])
print("New Dataframe\n")
print(new_df)

How to Drop Rows with missing values or NaN in all the selected columns in Pandas Dataframe

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        NaN   81.0
3  Abhay   NaN  Rajasthan    NaN
4  Ajjet  21.0      Delhi   74.0
5    NaN   NaN        NaN    NaN
6   Aman   NaN        NaN   76.0 

New Dataframe

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

Here we see that only row 7 has NaN value in both the columns hence it is dropped, while row 3 and row 6 have NaN value only in the age column hence it is not dropped.

So these are the methods to drop rows having all values as NaN or selected value as NaN.

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 Pandas – Remove Contents from a Dataframe

Pandas: Drop Rows With NaN/Missing Values in any or Selected Columns of Dataframe Read More »

Program to Check if two Lines are Parallel or Not

Python Program to Check if two Lines are Parallel or Not

In the previous article, we have discussed Python Program to Find the Greatest Digit in a Number.
Parallel Lines :

If two lines remain the same distance apart along their entire length, they are said to be parallel. They will not meet no matter how far you stretch them. These lines are denoted by the equations ax+by=c.

The line equation is ax+by=c, where an is the x coefficient and b is the y coefficient. If the slopes of two lines are equal, we say they are parallel. As a result, we must determine the slope, which is “rise over run.”

The straight-line equation is y=mx+c, where m is the slope. Take a1,b1,c1 and a2,b2,c2 from the user and see if they are parallel.

Given the values of equations of two lines, and the task is to check if the given two lines are parallel or not.

Examples:

Example 1:

Input:

a1=4, b1=8, c1=13
a2=2, b2=4, c2=7

Output:

The given lines are parallel to each other

Example 2:

Input:

a1=8, b1=0, c1=9
a2=8, b2=0, c2=11

Output:

The given lines are parallel to each other

Program to Check if two Lines are Parallel or Not

Below are the ways to check if the given two lines are parallel or not.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the values of a1,b1,c1 as static input and store it in three separate variables.
  • Give the values of a2,b2,c2 as static input and store it in three separate variables.
  • We can Check if the slopes of the given two lines are equal by formula (a1/b1 == a2/b2).
  • Create a function checkParallel() which accepts the 6 parameters (First and second line x,y,z coordinates)
  • Inside the checkParallel() function.
  • Check if both lines y coordinates are not equal to 0 using the If conditional Statement.
  • If it is true then check a1/b1 is equal to a2/b2 using another Nested If conditional Statement.
  • If it is true then return True
  • Else return False.
  • If parent If conditional statement is false then inside the else statement check if first line and second line x and y coordinates are equal or not using the nested If conditional statement.
  • If it is true then return True else return False.
  • Pass the a1,b1,c1,a2,b2,c2 as the arguments to checkParallel() function inside the if Conditional statement.
  • If it is true then print those lines are parallel.
  • Else they are not parallel.
  • The Exit of the Program.

Below is the implementation:

#Create a function checkParallel() which accepts the 6 parameters
#(First and second line x,y,z coordinates)
#We can Check if the slopes of the given two lines are equal by formula (a1/b1 == a2/b2).
def checkParallel(a1,b1,c1,a2,b2,c2):
    #Inside the checkParallel() function.
    #Check if both lines y coordinates are not equal to 0 
    #using the If conditional Statement.
    if(b1!=0 and b2!=0):
        #If it is true then check a1/b1 is equal to a2/b2 
        #using another Nested If conditional Statement.
        if(a1/b1==a2/b2):
            #If it is true then return True
            return True
        else:
            #Else return False.
            return False
    #If parent If conditional statement is false then inside the else statement 
    
    else:
      #check if first line and second line x and y coordinates are equal
      #or not using the nested If conditional statement.
      if(a1==a2 and b1==b2):
     	 #If it is true then return True else return False.
          return True
      else:
          return False
#Give the values of a1,b1,c1  as static input 
#and store it in three separate variables.
a1,b1,c1=4,8,13
#Give the values of a2,b2,c2  as static input 
#and store it in three separate variables.
a2,b2,c2=2,4,7
#Pass the a1,b1,c1,a2,b2,c2 as the arguments to checkParallel() function
#inside the if Conditional statement.
if(checkParallel(a1,b1,c1,a2,b2,c2)):
  #If it is true then print those lines are parallel.
  print('The given lines are parallel to each other')
else:
  #Else they are not parallel.
  print('The given lines are not parallel to each other')

Output:

The given lines are parallel to each other

Method #2: Using For Loop (User Input)

Approach:

  • Give the values of a1,b1,c1 as user input using map(),int(),split() functions and store it in three separate variables.
  • Give the values of a2,b2,c2 as user input using map(),int(),split() functions and store it in three separate variables.
  • We can Check if the slopes of the given two lines are equal by formula (a1/b1 == a2/b2).
  • Create a function checkParallel() which accepts the 6 parameters (First and second line x,y,z coordinates)
  • Inside the checkParallel() function.
  • Check if both lines y coordinates are not equal to 0 using the If conditional Statement.
  • If it is true then check a1/b1 is equal to a2/b2 using another Nested If conditional Statement.
  • If it is true then return True
  • Else return False.
  • If parent If conditional statement is false then inside the else statement check if first line and second line x and y coordinates are equal or not using the nested If conditional statement.
  • If it is true then return True else return False.
  • Pass the a1,b1,c1,a2,b2,c2 as the arguments to checkParallel() function inside the if Conditional statement.
  • If it is true then print those lines are parallel.
  • Else they are not parallel.
  • The Exit of the Program.

Below is the implementation:

#Create a function checkParallel() which accepts the 6 parameters
#(First and second line x,y,z coordinates)
#We can Check if the slopes of the given two lines are equal by formula (a1/b1 == a2/b2).
def checkParallel(a1,b1,c1,a2,b2,c2):
    #Inside the checkParallel() function.
    #Check if both lines y coordinates are not equal to 0 
    #using the If conditional Statement.
    if(b1!=0 and b2!=0):
        #If it is true then check a1/b1 is equal to a2/b2 
        #using another Nested If conditional Statement.
        if(a1/b1==a2/b2):
            #If it is true then return True
            return True
        else:
            #Else return False.
            return False
    #If parent If conditional statement is false then inside the else statement 
    
    else:
      #check if first line and second line x and y coordinates are equal
      #or not using the nested If conditional statement.
      if(a1==a2 and b1==b2):
          #If it is true then return True else return False.
          return True
      else:
          return False
#Give the values of a1,b1,c1 as user input using map(),int(),split() functions 
#and store it in three separate variables.
a1,b1,c1=map(int,input('Enter some random x y z coordinates separated by spaces = ').split())                    
#Give the values of a2,b2,c2 as user input using map(),int(),split() functions 
#and store it in three separate variables.
a2,b2,c2=map(int,input('Enter some random x y z coordinates separated by spaces = ').split())
#Pass the a1,b1,c1,a2,b2,c2 as the arguments to checkParallel() function
#inside the if Conditional statement.
if(checkParallel(a1,b1,c1,a2,b2,c2)):
  #If it is true then print those lines are parallel.
  print('The given lines are parallel to each other')
else:
  #Else they are not parallel.
  print('The given lines are not parallel to each other')

Output:

Enter some random x y z coordinates separated by spaces = 8 0 9
Enter some random x y z coordinates separated by spaces = 8 0 11
The given lines are parallel to each other

They are parallel to each other

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 if two Lines are Parallel or Not Read More »

Program to invert a Dictionary

Python Program to invert a Dictionary

In the previous article, we have discussed Python Program to Check if two Lines are Parallel or Not
Dictionary in python:

Python includes a class dictionary, which is typically defined as a set of key-value pairs. In Python, inverting a dictionary means swapping the key and value in the dictionary.

One thing is certain: complexity can be found in all of the different ways of storing key-value pairs. That is why dictionaries are used.

Python dictionaries are mutable collections of things that contain key-value pairs. The dictionary contains two main components: keys and values. These keys must be single elements, and the values can be of any data type, such as list, string, integer, tuple, and so on. The keys are linked to their corresponding values. In other words, the values can be retrieved using their corresponding keys.

A dictionary is created in Python by enclosing numerous key-value pairs in curly braces.

For example :

dictionary ={‘monday’:1, ‘tuesday’:2, ‘wednesday’:3}

The output after inverting the dictionary is { 1: [‘monday’] , 2: [‘tuesday’] , 3: [‘wednesday’] }

Given a dictionary, and the task is to invert the given dictionary.

Examples:

Example1:

Input:

Given dictionary = {10: 'jan', 20: 'feb', 30: 'march', 40: 'April', 50: 'may'}

Output:

The inverse of the given dictionary =  {'jan': [10], 'feb': [20], 'march': [30], 'April': [40], 'may': [50]}

Example 2:

Input:

Given dictionary = {'monday': 1, 'tuesday': 2, 'wednesday': 3}

Output:

The inverse of the given dictionary = {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Program to invert a Dictionary in Python

Below are the ways to invert a given dictionary

Method #1: Using For Loop (Static Input)

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {'monday': 1, 'tuesday': 2, 'wednesday': 3}
# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

The inverse of the given dictionary =  {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Method #2: Using For Loop (User Input)

Approach:

  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee

# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

Enter some random number of keys of the dictionary = 5
Enter key and value separated by spaces = hello 785
Enter key and value separated by spaces = this 100
Enter key and value separated by spaces = is 900
Enter key and value separated by spaces = btechgeeks 500
Enter key and value separated by spaces = python 400
The inverse of the given dictionary = {'785': ['hello'], '100': ['this'], '900': ['is'], '500': ['btechgeeks'], '400': ['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.

Python Program to invert a Dictionary Read More »

Program Enter ‘’ Between two Identical Characters in a String

Python Program Enter ‘*’ Between two Identical Characters in a String

In the previous article, we have discussed Python Program to invert a Dictionary
Given a String and the task is to enter ‘*’ between two identical characters.

Example :

Given string = btechgeeks

Output: btechge*eks

Explanation: Since both the e’s are identical and next to each other. so, we enter a ‘*’ in between them.

Examples:

Example1:

Input:

Given string = "good morning btechgeekss"

Output:

The given string after entering '*' between two identical characters= go*od morning btechge*eks*

Example 2:

Input:

Given string = "aabcddeefghii"

Output:

The given string after entering '*' between two identical characters= a*abcd*de*efghi*

Program Enter ‘*’ Between two Identical Characters in a String

Below are the ways to enter ‘*’ between two identical characters in a given String.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a new empty string say ‘new_str’and store it in another variable.
  • Take a variable and initialize its value with ‘0’ and store it in another variable.
  • Loop from ‘0’ to the length of the given string -1 using for loop and len() function.
  • Concat the new_str with the iterator value of the given string and store it in the same variable ‘new_str’.
  • Check if the iterator value of the given input string is equal to the iterator+1 value of the given input string using the if conditional statement.
  • If the statement is true, concatenate the ‘new_str’ with the ‘*’ symbol and store it in the same variable ‘new_str’.
  • Print the variable ‘new_str’ to enter ‘*’ between two identical characters in a given String.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "good morning btechgeekss"
# Take a new empty string say 'new_str'and store it in another variable.
new_str = ""
# Take a variable and initialize its value with '0' and store it in another variable.
itr = 0
# Loop from '0' to the length of the given string -1 using for loop and len() function.
for itr in range(0, len(gvn_str)-1):
    # Concat the new_str with the iterator value of the given string and
    # store it in the same variable 'new_str'
    new_str = new_str + gvn_str[itr]
# Check if the iterator value of the given input string is equal to the iterator+1 value
# of the given input string using the if conditional statement.
    if(gvn_str[itr] == gvn_str[itr+1]):
      # If the statement is true, concat the 'new_str' with the '*' symbol and
      # store it in the same variable 'new_str'.
        new_str += '*'
# Print the variable 'new_str' to enter '*' between two identical characters in a
# given String.
print("The given string after entering '*' between two identical characters=", new_str)

Output:

The given string after entering '*' between two identical characters= go*od morning btechge*eks*

Method #2: Using For Loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a new empty string say ‘new_str’and store it in another variable.
  • Take a variable and initialize its value with ‘0’ and store it in another variable.
  • Loop from ‘0’ to the length of the given string -1 using for loop and len() function.
  • Concat the new_str with the iterator value of the given string and store it in the same variable ‘new_str’.
  • Check if the iterator value of the given input string is equal to the iterator+1 value of the given input string using the if conditional statement.
  • If the statement is true, concatenate the ‘new_str’ with the ‘*’ symbol and store it in the same variable ‘new_str’.
  • Print the variable ‘new_str’ to enter ‘*’ between two identical characters in a given String.
  • The Exit of the program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Take a new empty string say 'new_str'and store it in another variable.
new_str = ""
# Take a variable and initialize its value with '0' and store it in another variable.
itr = 0
# Loop from '0' to the length of the given string -1 using for loop and len() function.
for itr in range(0, len(gvn_str)-1):
    # Concat the new_str with the iterator value of the given string and
    # store it in the same variable 'new_str'
    new_str = new_str + gvn_str[itr]
# Check if the iterator value of the given input string is equal to the iterator+1 value
# of the given input string using the if conditional statement.
    if(gvn_str[itr] == gvn_str[itr+1]):
      # If the statement is true, concat the 'new_str' with the '*' symbol and
      # store it in the same variable 'new_str'.
        new_str += '*'
# Print the variable 'new_str' to enter '*' between two identical characters in a
# given String.
print("The given string after entering '*' between two identical characters=", new_str)

Output:

Enter some random string = aabcddeefghii
The given string after entering '*' between two identical characters= a*abcd*de*efghi*

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 Enter ‘*’ Between two Identical Characters in a String Read More »