Python

While Loop with Examples

Python: While Loop with Examples

While Loops are used in Python to execute a set of statements over and over until a condition is met.. When the condition is met, the line immediately following the loop in the programme is executed. Indefinite iteration is demonstrated by the while loop. The term “indefinite iteration” refers to the fact that the number of times the loop is executed is not specified explicitly in advance.

While Loop in Python

1)Syntax:

while expression:
    statement(s)

2)Working of while loop

After a programming construct, all statements indented by the same number of character spaces are considered to be part of a single block of code.. Python’s method of grouping statements is indentation. When a while loop is run, expression is evaluated in a Boolean context and, if true, the loop body is executed. The expression is then checked again, and if it is still true, the body is executed again, and so on until the expression becomes false.

Using while loop to print first n natural numbers. let us take n=15

Below is the implementation: 

# using while loop to print natural numbers upto n
n = 15
# let us take a temp variable to 1 as natural numbers starts from 1
temp = 1
# using while loop
while(temp <= n):
    # printing temp variable
    print(temp)
    # increment the temp by 1
    temp = temp+1

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

4)Multiple conditions in while loop

In a while statement, we can have multiple conditions, and we can use ‘and’ and ‘or’ with these conditions.

Below is the implementation: 

# using while loop to print even natural numbers upto n
n = 15
# let us take a temp variable to 2 as natural numbers starts from 2
temp = 2
# using while loop
while(temp <= n and temp % 2 == 0):
    # printing temp variable
    print(temp)
    # increment the temp by 2
    temp = temp+2

Output:

2
4
6
8
10
12
14

5)While loop with else

In Python, we can have while…else blocks similar to if…else blocks, i.e., an else block after a while block.

The while loop will execute statements from the white suite multiple times until the condition is evaluated as False. When the condition in the while statement evaluates to False, control moves to the else block, where all of the statements in the else suite are executed.

Ex: Printing first n natural numbers and printing 0 at last.

Below is the implementation: 

# using while loop to print natural numbers upto n
n = 10
# let us take a temp variable to 1 as natural numbers starts from 1
temp = 1
# using while loop
while(temp <= n):
    # printing temp variable
    print(temp)
    # increment the temp by 1
    temp = temp+1
else:
    print(0)

Output:

1
2
3
4
5
6
7
8
9
10
0

Related Programs:

Python: While Loop with Examples Read More »

Sort a Dictionary by Value

Python: Sort a Dictionary by Value

Dictionaries are the implementation by Python of a data structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.

The list of key value pairs in curly braces that is separated by comma defines a dictionary. Column ‘:’ separates the value of each key.

A dictionary cannot be sorted only to get a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you need an ordered data type, which is a list—probably a list of tuples.

Examples:

Sorting values in ascending order:

Input:

dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}

Output:

is : 20
Platform : 25
this : 70
BTechGeeks : 100

Sorting values in descending order:

Input:

dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}

Output:

BTechGeeks : 100
this : 70
Platform : 25
is : 20

Sort a Dictionary by Value in Python

1)Sorted() function

Sorting any sequence in Python is a breeze thanks to the built-in method sorted(), which does all of the heavy lifting for you.
Sorted() sorts any sequence (list, tuple) and always returns a list with the elements sorted in the same order as the original sequence.

Syntax:

sorted(iterable, key, reverse)

Parameters:

sorted accepts three parameters, two of which are optional.

Iterable:  a sequence (list, tuple, or string) or a collection (dictionary, set, or frozenset) or any other iterator that must be sorted.
Key(optional):   A function that can be used as a key or as the basis for sort comparison.
Reverse(optional):   If set to true, the iterable is sorted in reverse (descending) order; otherwise, it is set to false.

2)Using sorted() +items() + Lambda function

We’ll use the sorted() function and transfer a key function that returns the first index element of the tuple, i.e. the value field from the key/value pair, to sort dictionary elements by value.

Below is the implementation:

# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in
# using key to sort by values
for i in sorted(dictitems, key=lambda x: x[1]):
    # print key and value
    print(i[0], ":", i[1])

Output:

is : 20
Platform : 25
this : 70
BTechGeeks : 100

3)Using sorted() +items() + Lambda function to sort in reverse order

This can be accomplished by simply passing an attribute to the sorted() function, such as reverse=True.

Below is the implementation:

# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in
# using key to sort by values
for i in sorted(dictitems, key=lambda x: x[1], reverse=True):
    # print key and value
    print(i[0], ":", i[1])

Output:

BTechGeeks : 100
this : 70
Platform : 25
is : 20

4)Using sorted() +items() + itemgetter in Python

To achieve similar functionality, Itemgetter can be used instead of the lambda function. The same as sorted() and lambda, but with a different internal implementation. It takes dictionary keys and converts them to tuples. It reduces overhead while also being faster and more efficient. To function, the “operator” module must be imported.

The itemgetter object can be passed as a key argument to the sorted() function to retrieve the value field from each key-value item of the dictionary while sorting.

Below is the implementation:

import operator
# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# using itemgetter
dictionary = dict(sorted(dictionary.items(),
                         key=operator.itemgetter(1)))
# print dictionary
print(dictionary)

Output:

{'is': 20, 'Platform': 25, 'this': 70, 'BTechGeeks': 100}

5)Using sorted() +items() + itemgetter  to sort in descending order in Python

This can be accomplished by simply passing an attribute to the sorted() function, such as reverse=True.

Below is the implementation:

import operator
# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# using itemgetter
dictionary = dict(sorted(dictionary.items(),
                         key=operator.itemgetter(1), reverse=True))
# print dictionary
print(dictionary)

Output:

{'BTechGeeks': 100, 'this': 70, 'Platform': 25, 'is': 20}

Related Programs:

Python: Sort a Dictionary by Value Read More »

How to Unpack List, Tuple or Dictionary to Function arguments using args and kwargs

Python : How to Unpack List, Tuple or Dictionary to Function arguments using * and **

Unpack elements in a list or tuple to function arguments

1)Args(*)

In Python function definitions, the special syntax *args is used to pass a variable number of arguments to a function. It is used to pass a variable-length, non-keyworded argument list.

To take in a variable number of arguments, the syntax is to use the symbol *; by convention, it is often used with the word args.
*args enables you to accept more arguments than the number of formal arguments you previously defined. With *args, you can add any number of extra arguments to your existing formal parameters (including zero extra arguments).
For instance, suppose we want to create a multiply function that can take any number of arguments and multiply them all together. It is possible.

Example:

i) Unpacking a list

Below is the implementation:

# givenlist
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# unpack the list
print(*givenlist)

Output:

hello this is BTechGeeks

ii)Unpacking a tuple

Below is the implementation:

# giventuple
giventuple = ('hello', 'this', 'is', 'BTechGeeks')
# unpack the tuple
print(*giventuple)

Output:

hello this is BTechGeeks

However, we must ensure that the elements of the list or tuple are exactly equal to function parameters. Otherwise, it will result in an error. As a result, it is commonly used with functions that accept variable length arguments.

Below is the implementation:

def calculateSum(*args):
    # Arguments of variable length are accepted by this function.
    num = len(args)
    if num == 0:
        return 0
    sumargs = 0
    for element in args:
        sumargs += element
    return sumargs


list1 = [1, 2, 3]
# passing list to calculateSum function
print(calculateSum(*list1))
list2 = [1, 2, 3, 4, 5, 6, 7]
# passing list to calculateSum function
print(calculateSum(*list2))

Output:

6
28

2)Kwargs(**)

In Python function definitions, the special syntax **kwargs is used to pass a keyworded, variable-length argument list. We call ourselves kwargs with a double star. The reason for this is that the double star allows us to pass keyword arguments through (and any number of them).

** is another symbol provided by Python. When it is prefixed with a dictionary, all of the key value pairs in the dictionary are unpacked to function arguments.

Examples:

1)

Below is the implementation:

def printDict(price, name, Model):
    print("price =", price)
    print("name =", name)
    print("Model =", Model)


# given dictionary
dictionary = {'price': 100, 'name': 'Apple', 'Model': '12pro'}
# printing dictionary arguments using kwargs**
printDict(**dictionary)

Output:

price = 100
name = Apple
Model = 12pro

Related Programs:

Python : How to Unpack List, Tuple or Dictionary to Function arguments using * and ** Read More »

Remove all Numbers from String

Python: Remove all Numbers from String

A Python string is a collection of characters surrounded by single, double, or triple quotes. The computer does not understand the characters; instead, it stores the manipulated character as a combination of 0’s and 1’s internally.

Examples:

Input:

string = "This is 2021 BTech21Geeks"

Output:

This is  BTechGeeks

Delete all Numbers from the string

There are several ways to remove all numbers from the string some of them are:

Method #1:Using string.join() method

The string.join(iterable) method takes an iterable object as input, joins its elements together using the string’s value as a separator, and returns the resulting string as output.

To remove numbers from the string, we will first iterate through it and select non-digit values, which we will then pass to the string.

To join them, use the join() method and output the resulting string with non-digit characters.

Below is the implementation:

# given string
string = "This is 2021 BTech21Geeks"
# using string.join() method by traversing the string and element is not digit
string = ''.join((element for element in string if not element.isdigit()))
# print the string
print(string)

Output:

This is  BTechGeeks

Method #2:Using translate() function

This method makes use of the string Python library. maketrans() uses a string object to separate numbers from the given string. Following that, a translation table is created in which each digit character, i.e. ‘0’ to ‘9,’ is mapped to None, and this translation table is passed to the translate() function.

The example below creates a translation table and replaces characters in a string based on this table, removing all numbers from the string.

Below is the implementation:

import string
# given string
string = "This is 2021 BTech21Geeks"

# the digits in string  are mapped to empty character
table = str.maketrans('', '', string.digits)

# remove all numbers from string
string = string.translate(translation_table)
# print the string
print(string)

Output:

This is  BTechGeeks

Method #3:Using Regex

Python includes a regex module with a built-in function sub() for removing numbers from strings. This method uses a replacement string to replace all occurrences of the given pattern in the string. If the pattern is not found in the string, the same string is returned.

In the following example, we use r'[0-9]’ as a pattern and an empty string as a replacement string. This pattern matches all of the numbers in the given string, and the sub() function replaces all of the digits that match with an empty string. It then deletes all of the numbers that match.

Below is the implementation:

import re
# given string
string = "This is 2021 BTech21Geeks"
# digits pattern
digitspattern = r'[0-9]'

# Replace all of the digits in the string with an empty string.
string = re.sub(digitspattern, '', string)

# print the string
print(string)

Output:

This is  BTechGeeks

Method #4:Using filter() and join()

In the generating expression, this example employs the filter() and lambda functions. It filters or deletes all of the numbers from the given string and then joins the remaining characters to form a new string.

The original string and the lambda expression are passed to the filter() function as arguments. We started by removing all digit characters from a string, then we joined all of the remaining characters.

Below is the implementation:

# given string
string = "This is 2021 BTech21Geeks"
# removing all digits
string = ''.join(filter(lambda x: not x.isdigit(), string))

# print the string
print(string)

Output:

This is  BTechGeeks

Related Programs:

Python: Remove all Numbers from String Read More »

Set add() vs update()

Python Set: add() vs update()

A set in Python is a data structure that is analogous to a set in mathematics. It can have any number of elements; the order of the elements in a set is undefined. You can add and delete elements from a set, iterate through the set’s elements, and perform standard set operations (union, intersection, difference). Aside from that, you can see if an element is a member of a set.

In contrast to arrays, where the elements are stored in an ordered list, the order of elements in a set is undefined (moreover, the set elements are usually not stored in order of appearance in the set; this allows checking if an element belongs to a set faster than just going through all the elements of the set).

Add vs Update in Set

In this article, we will look at the main differences between Python’s add() and update() functions for Set.

1)add() function

If the element is not already present in the set, the set add() method adds it.

Syntax:

set.add(element)

Parameters:

add() accepts a single parameter (element) that must be added to the set.

Return:

The add() method does not return any value.

2)update() function

set’s update() function adds elements from another set (passed as an argument) to the set.

Syntax:

set.update(*args)

Parameters:

The Update() method only accepts one argument. A set, list, tuples, or dictionary can be used as the single argument. It converts and adds to the set automatically.

Return:

This method simply adds args to set and returns null.

3) add() vs update() difference

  • To add a single element, use the add() function. To add multiple elements to a set, use the update() function.
  • add() is quicker than update().
  • Only immutable parameters are accepted by add (). In contrast, accepts iterable sequences.
  • add() only takes one parameter, whereas update() can take multiple sequences.

We will discuss this one by one

4)Difference #1:Number of items to be added to set

i)adding single element using add()

We can only add one element to the set using the add() function.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTeechGeeks'}
# adding element to set using add()
givenset.add('Python')
# print the set
print(givenset)

Output:

{'hello', 'BTeechGeeks', 'this', 'is', 'Python'}

ii)adding multiple elements using update()

In contrast, the update() function can be used to add multiple elements to the set in a single line.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTeechGeeks'}
# adding elements to set using update()
givenset.update(['Python', '2021', 'platform'])
# print the set
print(givenset)

Output:

{'2021', 'platform', 'is', 'BTeechGeeks', 'this', 'Python', 'hello'}

5)Difference #2:Execution time

Add() adds a single element to the set, whereas update() iterates over the given sequences and adds them to the set. As a result, add() outperforms the update() function in terms of performance.

6)Difference #3: Mutable and immutable parameters in add() and update() function

i)add() function

The add() function accepts immutable arguments, which means that we can pass int, strings, bytes, frozen sets, tuples, or any other immutable object to it.

So, if we try to pass a mutable object, such as a list, to the add() function, we will get an error.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTeechGeeks'}
# adding elements to set using add()
givenset.add(['Python', '2021', 'platform'])
# print the set
print(givenset)

Output:

Traceback (most recent call last):
  File "/home/520c50fb7c3daaa8db99bf168af58f53.py", line 4, in <module>
    givenset.add(['Python', '2021', 'platform'])
TypeError: unhashable type: 'list'

ii)update() function

The update() function only accepts iterable sequences. If we pass a list to the update() function, it will add all of the elements in the list to the set.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTeechGeeks'}
# adding elements to set using update()
givenset.update(['Python', '2021', 'platform'])
# print the set
print(givenset)

Output:

{'2021', 'platform', 'is', 'BTeechGeeks', 'this', 'Python', 'hello'}

7)Difference #4:Adding multiple elements using update

We can only pass one argument to the add() function, and it will add that element to the set. In contrast, we can pass multiple arguments, i.e. multiple iterable sequences, when calling the update() function.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTeechGeeks'}
# adding elements to set using update()
givenset.update(['Python', '2021'], ['platform', 'online'], ('India', 122))
# print the set
print(givenset)

Output:

{'hello', 'is', '2021', 'platform', 'online', 122, 'India', 'Python', 'this', 'BTeechGeeks'}

Related Programs:

Python Set: add() vs update() Read More »

Find Duplicates in a list with Frequency Count and index positions

Python: Find Duplicates in a list with Frequency Count and index positions

A collection is an ordered list of values. There could be various types of values. A list is a mutable container. This means that existing ones can be added to, deleted from, or changed.

The Python list represents the mathematical concept of a finite sequence. List values are referred to as list items or list elements. The same value may appear multiple times in a list. Each event is regarded as a distinct element.

Given a list, the task is to find Duplicate elements in a list with their respective frequencies and index positions.

Example:

I)Without indices

Input:

givenlist = [1, 2, 3, 1, 2, 1, 5, 6, 7, 8, 9]

Output:

element = 1 frequency : 3
element = 2 frequency : 2

II)With Indices

Input:

givenlist = [1, 2, 3, 1, 2, 1, 5, 6, 7, 8, 9]

Output:

element = 1 frequency : 3 indices : [0, 3, 5]
element = 2 frequency : 2 indices : [1, 4]

Find Duplicates in a list

There are several ways to find duplicates in a list some of them are:

Method #1:Using set method

  • Remove all duplicates from the list by converting it to a set.
  • Now, traverse the set and use the count() function to determine the frequency of each element.
  • If the frequency is greater than 1 then print the element and frequency

Below is the implementation:

# givenlist
givenlist = [1, 2, 3, 1, 2, 1, 5, 6, 7, 8, 9]
# converting givenlist to set
setlist = set(givenlist)
# Traverse the set
for element in setlist:
    # counting the frequency of element if it is greater than 1 then print it
    frequency = givenlist.count(element)
    if(frequency > 1):
        # print the element and frequency
        print('element =', element, 'frequency :', frequency)

Output:

element = 1 frequency : 3
element = 2 frequency : 2

Time Complexity: O(n^2)

Method #2:Using dictionary

We’ll write a function that takes a list and prints the duplicate elements in that list, as well as their frequency counts.

Approach:

  • This function produces a new dictionary when it is called. The program then goes through each element in the provided list one by one. It examines each variable to see if it is present in the dictionary keys.
  • If the element does not appear in the dictionary keys, it is added to the dictionary as a key with the value of 1.
    If the element is present in dictionary keys, the value of that key is increased by one.
  • Traverse the dictionary
  • If the frequency is greater than 1 then print the element and frequency

Below is the implementation:

# function which print the duplicates
def printDuplicates(givenlist):
    # taking a empty dictionary
    freq = {}
    # Traverse the list
    for element in givenlist:
        # if the element is in freq dictionary then add its count
        if element in freq.keys():
            freq[element] += 1
        else:
            freq[element] = 1

    # Traverse the freq dictionary and print the duplicate elements and frequency
    for key in freq:
        # if value/count is greater than 1 the print it
        if(freq[key] > 1):
            print('element =', key, 'frequency :', freq[key])


# givenlist
givenlist = [1, 2, 3, 1, 2, 1, 5, 6, 7, 8, 9]
# passing list to printDuplicates function
printDuplicates(givenlist)

Output:

element = 1 frequency : 3
element = 2 frequency : 2

Time Complexity: O(n)

Method #3:Using Counter() function

We can use an iterable or any dict like mapping to construct a Counter class object. This Counter object keeps track of how many times each variable in the iterable has been counted. Let’s use the Counter object to locate and count duplicates in a list.

This function is similar to first two points in method 2

Below is the implementation:

from collections import Counter
# function which print the duplicates


def printDuplicates(givenlist):
    # using Counter function to calculate frequencies
    freq = Counter(givenlist)

    # Traverse the freq dictionary and print the duplicate elements and frequency
    for key in freq:
        # if value/count is greater than 1 the print it
        if(freq[key] > 1):
            print('element =', key, 'frequency :', freq[key])


# givenlist
givenlist = [1, 2, 3, 1, 2, 1, 5, 6, 7, 8, 9]
# passing list to printDuplicates function
printDuplicates(givenlist)

Output:

element = 1 frequency : 3
element = 2 frequency : 2

Time Complexity: O(n)

Method #4:Finding indices and frequency of duplicate elements

Approach:

  • let us take starting index as 0
  • This function produces a new dictionary when it is called. The program then goes through each element in the provided list one by one. It examines each variable to see if it is present in the dictionary keys.
  • Then iterates through each element in the list one by one, keeping track of the index positions.
  • Then, for each element, it checks to see if it already exists in the dictionary keys.
  • If it doesn’t, it creates a new key-value pair in the dictionary, with the element as the key and a list object of two items as the value. 1)count as 1 2) index list with current index position
  • If the element is found in the dictionary keys, the frequency count in the value field is increased, and the index location in the index list is added.
  • Increment the index by 1 for every iteration
  • Traverse the dictionary
  • If the frequency is greater than 1 then print the element and frequency and indices

Below is the implementation:

def printDuplicates(givenlist):
    # taking a empty dictionary
    freq = {}
    # taking index =0
    index = 0
    # Traverse the list
    for element in givenlist:
        # if the element is in freq dictionary then add its count and index
        if element in freq.keys():
            freq[element][0] += 1
            freq[element][1].append(index)
        else:
            freq[element] = [1, [index]]
        # increment the index
        index += 1

    # Traverse the freq dictionary and print the duplicate elements and frequency
    for key in freq:
        # if value/count is greater than 1 the print it
        if(freq[key][0] > 1):
            print('element =', key, 'frequency :',
                  freq[key][0], 'indices :', freq[key][1])


# givenlist
givenlist = [1, 2, 3, 1, 2, 1, 5, 6, 7, 8, 9]
# passing list to printDuplicates function
printDuplicates(givenlist)

Output:

element = 1 frequency : 3 indices : [0, 3, 5]
element = 2 frequency : 2 indices : [1, 4]

Time Complexity: O(n)

 
Related Programs:

Python: Find Duplicates in a list with Frequency Count and index positions Read More »

Pandas : Get unique values in columns of a Dataframe in Python

How to get unique values in columns of a Dataframe in Python ?

To find the Unique values in a Dataframe we can use-

  1. series.unique(self)- Returns a numpy array of Unique values
  2. series.nunique(self, axis=0, dropna=True )- Returns the count of Unique values along different axis.(If axis = 0 i.e. default value, it checks along the columns.If axis = 1, it checks along the rows)

To test these functions let’s use the following data-

     Name      Age       City          Experience

a     jack       34.0     Sydney             5
b     Riti        31.0      Delhi               7
c     Aadi      16.0       NaN               11
d    Mohit    31.0       Delhi               7
e    Veena    NaN      Delhi               4
f   Shaunak  35.0     Mumbai           5
g    Shaun    35.0    Colombo          11

Finding unique values in a single column :

To get the unique value(here age) we use the unique( ) function on the column

CODE:-

#Program :

import numpy as np
import pandas as pd
# Data list
emp = [('jack', 34, 'Sydney', 5) ,
         ('Riti', 31, 'Delhi' , 7) ,
         ('Aadi', 16, np.NaN, 11) ,
         ('Mohit', 31,'Delhi' , 7) ,
         ('Veena', np.NaN, 'Delhi' , 4) ,
         ('Shaunak', 35, 'Mumbai', 5 ),
         ('Shaun', 35, 'Colombo', 11)
          ]
# Object of Dataframe class created
empObj = pd.DataFrame(emp, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# Obtain the unique values in column 'Age' of the dataframe
uValues = empObj['Age'].unique()
# empObj[‘Age’] returns a series object of the column ‘Age’
print('The unique values in column "Age" are ')
print(uValues)
Output :
The unique values in column "Age" are
[34. 31. 16. nan 35.]

Counting unique values in a single column :

If we want to calculate the number of Unique values rather than the unique values, we can use the .nunique( ) function.

CODE:-

#Program :

import numpy as np
import pandas as pd
# Data list
emp = [('jack', 34, 'Sydney', 5) ,
('Riti', 31, 'Delhi' , 7) ,
('Aadi', 16, np.NaN, 11) ,
('Mohit', 31,'Delhi' , 7) ,
('Veena', np.NaN, 'Delhi' , 4) ,
('Shaunak', 35, 'Mumbai', 5 ),
('Shaun', 35, 'Colombo', 11)
]
# Object of Dataframe class created
empObj = pd.DataFrame(emp, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# Counting the  unique values in column 'Age' of the dataframe
uValues = empObj['Age'].nunique()
print('Number of unique values in 'Age' column :')
print(uValues)
Output :
Number of unique values in 'Age' column :
4

Including NaN while counting the Unique values in a column :

NaN’s are not counted by default in the .nunique( ) function. To also include NaN we have to pass the dropna argument

CODE:-

#Program :

import numpy as np
import pandas as pd
# Data list
emp = [('jack', 34, 'Sydney', 5) ,
('Riti', 31, 'Delhi' , 7) ,
('Aadi', 16, np.NaN, 11) ,
('Mohit', 31,'Delhi' , 7) ,
('Veena', np.NaN, 'Delhi' , 4) ,
('Shaunak', 35, 'Mumbai', 5 ),
('Shaun', 35, 'Colombo', 11)
]
# Object of Dataframe class created
empObj = pd.DataFrame(emp, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# Counting the unique values in column 'Age' also including NaN
uValues = empObj['Age'].nunique(dropna=False)
print('Number of unique values in 'Age' column including NaN:)
print(uValues)
Output :
Number of unique values in 'Age' column including NaN:
5

Counting unique values in each column of the dataframe :

To count the number of Unique values in each columns

CODE:-

#Program :

import numpy as np
import pandas as pd
# Data list
emp = [('jack', 34, 'Sydney', 5) ,
('Riti', 31, 'Delhi' , 7) ,
('Aadi', 16, np.NaN, 11) ,
('Mohit', 31,'Delhi' , 7) ,
('Veena', np.NaN, 'Delhi' , 4) ,
('Shaunak', 35, 'Mumbai', 5 ),
('Shaun', 35, 'Colombo', 11)
]
# Object of Dataframe class created
empObj = pd.DataFrame(emp, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# Counting the unique values in each column
uValues = empObj.nunique()
print('In each column the number of unique values are')
print(uValues)
Output :
In each column the number of unique values are
Name          7
Age           4
City          4
Experience    4
dtype: int64

To include the NaN, just pass dropna into the function.

Get Unique values in multiple columns :

To get unique values in multiple columns, we have to pass all the contents of columns as a series object into the .unique( ) function

CODE:-

#program :

import numpy as np
import pandas as pd
# Data list
emp = [('jack', 34, 'Sydney', 5) ,
('Riti', 31, 'Delhi' , 7) ,
('Aadi', 16, np.NaN, 11) ,
('Mohit', 31,'Delhi' , 7) ,
('Veena', np.NaN, 'Delhi' , 4) ,
('Shaunak', 35, 'Mumbai', 5 ),
('Shaun', 35, 'Colombo', 11)
]
# Object of Dataframe class created
empObj = pd.DataFrame(emp, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# Obtain the Unique values in multiple columns i.e. Name & Age
uValues = (empObj['Name'].append(empObj['Age'])).unique()
print('The unique values in column "Name" & "Age" :')
print(uValues)
Output :
The unique values in column "Name" & "Age" :
['jack' 'Riti' 'Aadi' 'Mohit' 'Veena' 'Shaunak' 'Shaun' 34.0 31.0 16.0 nan
35.0]

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

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

Pandas : Get unique values in columns of a Dataframe in Python Read More »

How to get & check data types of Dataframe columns in Python Pandas

How to get & check data types of dataframes columns in python pandas ?

In this article we will discuss different ways to get the data type of single or multiple columns.

Use Dataframe.dtype to get data types of columns in Dataframe :

In python’s pandas module provides Dataframe class as a container for storing and manipulating two-dimensional data which provides an attribute to get the data type information of each column.

This Dataframe.dtype returns a series mentioned with the data type of each column.

Let’s try with an example:

#Program :

import pandas as pd
import numpy as np
#list of tuples
game = [('riya',37,'delhi','cat','rose'),
   ('anjali',28,'agra','dog','lily'),
   ('tia',42,'jaipur','elephant','lotus'),
   ('kapil',51,'patna','cow','tulip'),
   ('raj',30,'banglore','lion','orchid')]
#Create a dataframe object
df = pd.DataFrame(game, columns=['Name','Age','Place','Animal','Flower'], index=['a','b','c','d','e'])
print(df)
Output:
     Name   Age     Place     Animal     Flower
a    riya      37        delhi       cat          rose
b   anjali    28        agra       dog          lily
c     tia      42        jaipur    elephant     lotus
d   kapil    51       patna       cow          tulip
e     raj      30     banglore     lion       orchid

This is the contents of the dataframe. Now let’s fetch the data types of each column in dataframe.

#Program :

import pandas as pd
import numpy as np
#list of tuples
game = [('riya',37,'delhi','cat','rose'),
   ('anjali',28,'agra','dog','lily'),
   ('tia',42,'jaipur','elephant','lotus'),
   ('kapil',51,'patna','cow','tulip'),
   ('raj',30,'banglore','lion','orchid')]
#Create a dataframe object
df = pd.DataFrame(game, columns=['Name','Age','Place','Animal','Flower'], index=['a','b','c','d','e'])
DataType = df.dtypes
print('Data type of each column:')
print(DataType)
Output:
Data type of each column:
Name      object
Age          int64
Place       object
Animal    object
Flower    object
dtype:     object

Get Data types of dataframe columns as dictionary :

#Program :

import pandas as pd
import numpy as np
#list of tuples
game = [('riya',37,'delhi','cat','rose'),
   ('anjali',28,'agra','dog','lily'),
   ('tia',42,'jaipur','elephant','lotus'),
   ('kapil',51,'patna','cow','tulip'),
   ('raj',30,'banglore','lion','orchid')]
#Create a dataframe object
df = pd.DataFrame(game, columns=['Name','Age','Place','Animal','Flower'], index=['a','b','c','d','e'])
#get a dictionary containing the pairs of column names and data types object
DataTypeDict = dict(df.dtypes)
print('Data type of each column :')
print(DataTypeDict)
Output:
Data type of each column  :{'Name': dtype('O'), 'Age': dtype('int64'), 'Place': dtype('O'), 'Animal': dtype('O'), 'Flower': dtype('O')}

Get the data type of a single column in dataframe :

By using Dataframe.dtypes we can also get the data type of a single column from a series of objects.

#Program :

import pandas as pd
import numpy as np
#list of tuples
game = [('riya',37,'delhi','cat','rose'),
   ('anjali',28,'agra','dog','lily'),
   ('tia',42,'jaipur','elephant','lotus'),
   ('kapil',51,'patna','cow','tulip'),
   ('raj',30,'banglore','lion','orchid')]
#Create a dataframe object
df = pd.DataFrame(game, columns=['Name','Age','Place','Animal','Flower'], index=['a','b','c','d','e'])
#get a dictionary containing the pairs of column names and data types object
DataTypeObj = df.dtypes['Age']
print('Data type of each column Age : ')
print(DataTypeObj)
Output :
Data type of each column Age :int64

Get list of pandas dataframe column names based on data types :

Suppose, we want a list of column names based on datatypes. Let’s take an example program whose data type is object(string).

import pandas as pd
import numpy as np
#list of tuples
game = [('riya',37,'delhi','cat','rose'),
('anjali',28,'agra','dog','lily'),
('tia',42,'jaipur','elephant','lotus'),
('kapil',51,'patna','cow','tulip'),
('raj',30,'banglore','lion','orchid')]
#Create a dataframe object
df = pd.DataFrame(game, columns=['Name','Age','Place','Animal','Flower'], index=['a','b','c','d','e'])

# Get  columns whose data type is object means string
filteredColumns = df.dtypes[df.dtypes == np.object]
# list of columns whose data type is object means string
listOfColumnNames = list(filteredColumns.index)
print(listOfColumnNames)
Output:
['Name', 'Place', 'Animal', 'Flower']

Get data types of a dataframe using Dataframe.info() :

Dataframe.info() function is used to get simple summary of a dataframe. By using this method we can get information about a dataframe including the index dtype and column dtype, non-null values and memory usage.

#program :

import pandas as pd
import numpy as np
#list of tuples
game = [('riya',37,'delhi','cat','rose'),
('anjali',28,'agra','dog','lily'),
('tia',42,'jaipur','elephant','lotus'),
('kapil',51,'patna','cow','tulip'),
('raj',30,'banglore','lion','orchid')]
#Create a dataframe object
df = pd.DataFrame(game, columns=['Name','Age','Place','Animal','Flower'], index=['a','b','c','d','e'])
df.info()
Output:
<class 'pandas.core.frame.DataFrame'>
Index: 5 entries, a to e
Data columns (total 5 columns): 
#   Column  Non-Null Count  Dtype 
---  ------  --------------  -----  
a   Name     5 non-null      object 
b   Age        5 non-null      int64  
c   Place      5 non-null      object 
d   Animal   5 non-null      object 
e   Flower   5 non-null      object
dtypes: int64(1), object(4)
memory usage: 240.0+ bytes

How to get & check data types of Dataframe columns in Python Pandas Read More »

Create NumPy Array from List, Tuple or List of Lists in Python

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

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

NumPy

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

numpy.array()

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

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

This method returns a numpy array.

numpy.asarray()

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

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

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

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

Create a numpy array from a list

  • Method 1-Using numpy.array()

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

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

Output

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

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

  • Method 2-Using numpy.asarray()

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

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

Output

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

Create a numpy array from a tuple

  • Method 1-Using numpy.array()

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

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

Output

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

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

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

Output

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

Create a 2d Numpy array from a list of list

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

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

Output

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

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

Create NumPy Array from List, Tuple or List of Lists in Python Read More »

String – Replace() Method

Python String – Replace() Method

A string is a character sequence.
A character is nothing more than a symbol. The English language, for example, has 26 characters.
Computers do not work with characters, but rather with numbers (binary). Despite the very fact that you simply see characters on your screen, they’re internally stored and manipulated as a series of 0s and 1s.
Encoding is the process of converting a character to a number, and decoding is the reverse process. ASCII and Unicode are two of the most common encodings.
A string in Python may be a sequence of Unicode characters. Unicode was created to include every character in all languages and to bring encoding uniformity. Python Unicode can teach you everything you need to know about Unicode.

String Replace() Function

1)replace() function

replace() is a built-in Python function that returns a copy of the string in which all occurrences of a substring are replaced with another substring.

Syntax:

given_string.replace(old, new, count)

Parameters:

  • old−This is an old substring that must get replaced .
  • new − this is often a replacement substring which will replace the old one.
  • max − Only the primary count occurrences are replaced if the optional argument max is provided.

Return:
This method returns a string copy during which all occurrences of substring old are replaced with new. Only the primary count occurrences are replaced if the optional argument max is provided.

2)Replace all instances of a character or string in a string:

Assume we have a string, and now replace all occurrences of ‘e’ with ‘q’.

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
    # using replace
    resultstring = string.replace(oldstring, replacestring)

    # return the final string
    return resultstring


# Driver code
# given string
string = "This is BTechGeeks new online learning platform"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 't'
# passing these strings to replaceString function
print(replaceString(string, oldstring, replacestring))

Output:

This is BTtchGttks ntw onlint ltarning platform

3)Replace only first two occurences of string:

Instead of replacing all occurrences of a character in a string, we can use the replace() function’s count argument to replace only the first few occurrences of a character.

Below is the implementation:

# Function which replaces the string
def replaceMultipleString(string, oldstring, replacestring):
    # using replace
    # providing count =2
    resultstring = string.replace(oldstring, replacestring, 2)

    # return the final string
    return resultstring


# Driver code
# given string
string = "Hello this is BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = '$$$'
# passing these strings to replaceMultipleString function
print(replaceMultipleString(string, oldstring, replacestring))

Output:

H$$$llo this is BT$$$chGeeks

4)Replace the first occurrence of a given substring in a string with another character

If we only want to replace the first occurrences of a substring in a string with another character or substring, we must use the replace() function with the count argument set to 1.

Below is the implementation:

# Function which replaces the string
def replaceMultipleString(string, oldstring, replacestring):
    # using replace
    # providing count =2
    resultstring = string.replace(oldstring, replacestring, 1)

    # return the final string
    return resultstring


# Driver code
# given string
string = "Hello this is BTechGeeks"
# string which needs to be replaced
oldstring = 'is'
# replacing string/new string
replacestring = 't'
# passing these strings to replaceMultipleString function
print(replaceMultipleString(string, oldstring, replacestring))

Output:

Hello tht is BTechGeeks

Related Programs:

Python String – Replace() Method Read More »