Author name: Shikha Mishra

Count occurrences of a value in NumPy array in Python

Count occurrences of a value in NumPy array in Python | numpy.count() in Python

Count Occurences of a Value in Numpy Array in Python: In this article, we have seen different methods to count the number of occurrences of a value in a NumPy array in Python. Check out the below given direct links and gain the information about Count occurrences of a value in a NumPy array in Python.

Python numpy.count() Function

The function of numpy.count()in python aid in the counts for the non-overlapping occurrence of sub-string in the specified range. The syntax for phyton numpy.count() function is as follows:

Syntax:

numpy.core.defchararray.count(arr, substring, start=0, end=None)

Parameters:

  • arr: array-like or string to be searched.
  • substring: substring to search for.
  • start, end: [int, optional] Range to search in.

Returns:

An integer array with the number of non-overlapping occurrences of the substring.

Example Code for numpy.count() Function in Python

numpy.count() function in python

# Python Program illustrating 
# numpy.char.count() method 
import numpy as np 
  
# 2D array 
arr = ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']
  
print ("arr : ", arr)
  
print ("Count of 'Aa'", np.char.count(arr, 'Aa'))
print ("Count of 'Aa'", np.char.count(arr, 'Aa', start = 8))

Output:

arr : ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']

Count of 'Aa' [1 1 1 1]
Count of 'Aa' [1 0 0 0]

Also Check:

How to count the occurrences of a value in a NumPy array in Python

Counting the occurrences of a value in a NumPy array means returns the frequency of the value in the array. Here are the various methods used to count the occurrences of a value in a python numpy array.

Use count_nonzero()

We use the count_nonzero()function to count occurrences of a value in a NumPy array, which returns the count of values in a given numpy array. If the value of the axis argument is None, then it returns the count.

Let’s take an example, count all occurrences of value ‘6’ in an array,

import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
print('Numpy Array:')
print(arr)
# Count occurrence of element '3' in numpy array
count = np.count_nonzero(arr == 6)
print('Total occurences of "6" in array: ', count)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Numpy Array:
[9 6 7 5 6 4 5 6 5 4 7 8 6 6 7]
Total occurences of "6" in array: 5

In the above example, you have seen that we applied a condition to the numpy array ie., arr==6, then it applies the condition on each element of the array and stores the result as a bool value in a new array.

Use sum()

In this, we are using thesum()function to count occurrences of a value in an array.

import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
print('Numpy Array:')
print(arr)
# Count occurrence of element '6' in numpy array
count = (arr == 6).sum()

print('Total occurences of "6" in array: ', count)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Numpy Array: [9 6 7 5 6 4 5 6 5 4 7 8 6 6 7]
Total occurences of "6" in array: 5

In the above example, we have seen if the given condition is true then it is equivalent to one in python so we can add the True values in the array to get the sum of values in the array.

Use bincount()

We usebincount()function to count occurrences of a value in an array.

import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
count_arr = np.bincount(arr)
# Count occurrence of element '6' in numpy array
print('Total occurences of "6" in array: ', count_arr[6])
# Count occurrence of element '5' in numpy array
print('Total occurences of "5" in array: ', count_arr[5])

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Total occurences of "6" in array: 5
Total occurences of "5" in array: 3

Convert numpy array to list and count occurrences of a value in an array

In this method, first we convert the array to a list and then we applycount()function on the list to get the count of occurrences of an element.

import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
# Count occurrence of element '6' in numpy array
count = arr.tolist().count(6)
print('Total occurences of "6" in array: ', count)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Total occurences of "6" in array:

Select elements from the array that matches the value and count them

We can choose only those elements from the numpy array that is similar to a presented value and then we can attain the length of this new array. It will furnish the count of occurrences of the value in the original array. For instance,

import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [5, 3, 5],
                    [4, 7, 8],
                    [3, 6, 2]] )
# Count occurrence of element '3' in each column
count = np.count_nonzero(matrix == 3, axis=0)
print('Total occurrences  of "3" in each column of 2D array: ', count)

Output: 

Total occurrences of "3" in each column of 2D array: [1 3 0]

Count occurrences of a value in 2D NumPy Array

We can use the count_nonzero() function to count the occurrences of a value in a 2D array or matrix.

import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [5, 6, 5],
                    [6, 7, 6],
                    [3, 6, 2]] )
# Count occurrence of element '6' in complete 2D Numpy Array
count = np.count_nonzero(matrix == 6)
print('Total occurrences of "6" in 2D array:')
print(count)

Output:

Total occurrences of "6" in 2D array: 4

Count occurrences of a value in each row of 2D NumPy Array

To count the occurrences of a value in each row of the 2D  array we will pass the axis value as 1 in the count_nonzero() function.

It will return an array containing the count of occurrences of a value in each row.

import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [6, 6, 5],
                    [4, 7, 6],
                    [3, 6, 2]] )
# Count occurrence of element '6' in each row
count = np.count_nonzero(matrix == 6, axis=1)
print('Total occurrences  of "6" in each row of 2D array: ', count)

Output:

Total occurrences of "6" in each row of 2D array: [0 0 2 1 1]

Count occurrences of a value in each column of 2D NumPy Array

In order to count the occurrences of a value in each column of the 2D NumPy array transfer the axis value as 0 in thecount_nonzero()function. After that, it will result in an array including the count of occurrences of a value in each column. For instance,

import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [5, 3, 5],
                    [4, 7, 8],
                    [3, 6, 2]] )
# Count occurrence of element '3' in each column
count = np.count_nonzero(matrix == 3, axis=0)
print('Total occurrences  of "3" in each column of 2D array: ', count)

Output:

Total occurrences of "3" in each column of 2D array: [1 3 0]

Count occurrences of a value in NumPy array in Python | numpy.count() in Python Read More »

How to sort a Numpy Array in Python

How to sort a Numpy Array in Python? | numpy.sort() in Python | Python numpy.ndarray.sort() Function

In this article, we are going to show you sorting a NumpyArray in descending and in ascending order or sorts the elements from largest to smallest value or smallest to largest value. Stay tuned to this page and collect plenty of information about the numpy.sort() in Python and How to sort a Numpy Array in Python?

Sorting Arrays

Giving arrays to an ordered sequence is called sorting. An ordered sequence can be any sequence like numeric or alphabetical, ascending or descending.

Python’s Numpy module provides two different methods to sort a numpy array.

numpy.ndarray.sort() method in Python

A member function of the ndarray class is as follows:

ndarray.sort(axis=-1, kind='quicksort', order=None)

This can be ordered through a numpy array object (ndarray) and it classifies the incorporated numpy array in place.

Do Check:

Python numpy.sort() method

One more method is a global function in the numpy module i.e.

numpy.sort(array, axis=-1, kind='quicksort', order=None)

It allows a numpy array as an argument and results in a sorted copy of the Numpy array.

Where,

Sr.No.Parameter & Description
1a

Array to be sorted

2axis

The axis along which the array is to be sorted. If none, the array is flattened, sorting on the last axis

3kind

Default is quicksort

4order

If the array contains fields, the order of fields to be sorted

Sort a Numpy Array in Place

The NumPy ndarray object has a function called sort() that we will use for sorting.

import numpy as np
# Create a Numpy array from list of numbers
arr = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
array = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
# Sort the numpy array inplace
array.sort()
print('Original Array : ', arr)
print('Sorted Array : ', array)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Original Array : [ 9 1 3 2 17 5 2 8 14]
Sorted Array : [ 1 2 2 3 5 8 9 14 17]

So in the above example, you have seen that usingarray.sort()we have sorted our array in place.

Sort a Numpy array in Descending Order

In the above method, we have seen that by default both numpy.sort() and ndarray.sort() sorts the numpy array in ascending order. But now, you will observe how to sort an array in descending order?

import numpy as np
# Create a Numpy array from list of numbers
arr = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
array = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
# Sort the numpy array inplace
array = np.sort(arr)[::-1]

# Get a sorted copy of numpy array (Descending Order)
print('Original Array : ', arr)
print('Sorted Array : ', array)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Original Array : [ 9 1 3 2 17 5 2 8 14]
Sorted Array : [17 14 9 8 5 3 2 2 1]

Sorting a numpy array with different kinds of sorting algorithms

While sorting sort() function accepts a parameter ‘kind’ that tells about the sorting algorithm to be used. If not provided then the default value is quicksort. To sort numpy array with another sorting algorithm pass this ‘kind’ argument.

import numpy as np
# Create a Numpy array from list of numbers
arr = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
array = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
# Sort the numpy array using different algorithms

#Sort Using 'mergesort'
sortedArr1 = np.sort(arr, kind='mergesort')

# Sort Using 'heapsort'
sortedArr2 = np.sort(arr, kind='heapsort')

# Sort Using 'heapsort'
sortedArr3 = np.sort(arr, kind='stable')

# Get a sorted copy of numpy array (Descending Order)
print('Original Array : ', arr)

print('Sorted Array using mergesort: ', sortedArr1)

print('Sorted Array using heapsort : ', sortedArr2)

print('Sorted Array using stable : ', sortedArr3)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Original Array : [ 9 1 3 2 17 5 2 8 14]
Sorted Array using mergesort: [ 1 2 2 3 5 8 9 14 17]
Sorted Array using heapsort : [ 1 2 2 3 5 8 9 14 17]
Sorted Array using stable : [ 1 2 2 3 5 8 9 14 17]

Sorting a 2D numpy array along with the axis

numpy.sort() and numpy.ndarray.sort() provides an argument axis to sort the elements along the axis.
Let’s create a 2D Numpy Array.

import numpy as np
# Create a 2D Numpy array list of list

arr2D = np.array([[8, 7, 1, 2], [3, 2, 3, 1], [29, 32, 11, 9]])

print(arr2D)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
[[ 8 7 1 2]
[ 3 2 3 1]
[29 32 11 9]]

Now sort contents of each column in 2D numpy Array,

import numpy as np
# Create a 2D Numpy array list of list

arr2D = np.array([[8, 7, 1, 2], [3, 2, 3, 1], [29, 32, 11, 9]])
arr2D.sort(axis=0)
print('Sorted Array : ')
print(arr2D)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Sorted Array :
[[ 3 2 1 1]
[ 8 7 3 2]
[29 32 11 9]]

So here is our sorted 2D numpy array.

How to sort a Numpy Array in Python? | numpy.sort() in Python | Python numpy.ndarray.sort() Function Read More »

Python Convert Matrix or 2D Numpy Array to a 1D Numpy Array

Python: Convert Matrix / 2D Numpy Array to a 1D Numpy Array | How to make a 2d Array into a 1d Array in Python?

This article is all about converting 2D Numpy Array to a 1D Numpy Array. Changing a 2D NumPy array into a 1D array returns in an array containing the same elements as the original, but with only one row. Want to learn how to convert 2d Array into 1d Array using Python? Then, stay tuned to this tutorial and jump into the main heads via the available links shown below:

Convert 2D Numpy array / Matrix to a 1D Numpy array using flatten()

Python Numpy provides a function flatten() to convert an array of any shape to a flat 1D array.

Firstly, it is required to import the numpy module,

import numpy as np

Syntax:

ndarray.flatten(order='C')
ndarray.flatten(order='F')
ndarray.flatten(order='A')

Order: In which items from the array will be read

Order=’C’: It will read items from array row-wise

Order=’F’: It will read items from array row-wise

Order=’A’: It will read items from array-based on memory order

Suppose we have a 2D Numpy array or matrix,

[7 4 2]
[5 3 6]
[2 9 5]

Which we have to convert in a 1D array. Let’s use this to convert a 2D numpy array or matrix to a new flat 1D numpy array,

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# get a flatten 1D copy of 2D Numpy array
flat_array = arr.flatten()
print('1D Numpy Array:')
print(flat_array)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

If we made any changes in our 1D array it will not affect our original 2D array.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# get a flatten 1D copy of 2D Numpy array
flat_array = arr.flatten()
print('1D Numpy Array:')
print(flat_array)
# Modify the flat 1D array
flat_array[0] = 50
print('Modified Flat Array: ')
print(flat_array)
print('Original Input Array: ')
print(arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

Modified Flat Array:
[50 4 2 5 3 6 2 9 5]

Original Input Array:
[[7 4 2]
[5 3 6]
[2 9 5]]

Also Check:

Convert 2D Numpy array to 1D Numpy array using numpy.ravel()

Numpy have  a built-in function ‘numpy.ravel()’ that accepts an array element as parameter and returns a flatten 1D array.

Syntax:

numpy.ravel(input_arr, order='C')

Let’s make use of this syntax to convert 2D array to 1D array,

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Get a flattened view of 2D Numpy array
flat_array = np.ravel(arr)
print('Flattened 1D Numpy array:')
print(flat_array)

Output:

Flattened 1D Numpy array:
[7 4 2 5 3 6 2 9 5]

If we made any changes in our 1D array using numpy.ravel() it will also affect our original 2D array.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Get a flattened view of 2D Numpy array
flat_array = np.ravel(arr)
print('Flattened 1D Numpy array:')
print(flat_array)
# Modify the 2nd element  in flat array
flat_array[1] = 12
# Changes will be reflected in both flat array and original 2D array
print('Modified Flattened 1D Numpy array:')
print(flat_array)
print('2D Numpy Array:')
print(arr)

Output:

Flattened 1D Numpy array:
[7 4 2 5 3 6 2 9 5]
Modified Flattened 1D Numpy array:
[ 7 12 2 5 3 6 2 9 5]
2D Numpy Array:
[[ 7 12 2]
[ 5 3 6]
[ 2 9 5]]

Convert a 2D Numpy array to a 1D array using numpy.reshape()

Numpy provides a built-in function reshape() to convert the shape of a numpy array,

It accepts three arguments-

  • a: Array which we have to be reshaped
  • newshape: Newshape can be a tuple or integer
  • order: The order in which items from the input array will be used
import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])

# convert 2D array to a 1D array of size 9
flat_arr = np.reshape(arr, 9)
print('1D Numpy Array:')
print(flat_arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

In the above example, we have pass 9 as an argument because there were a total of 9 elements (3X3) in the 2D input array.

numpy.reshape() and -1 size

This function can be used when the input array is too big and multidimensional or we just don’t know the total elements in the array. In such scenarios, we can pass the size as -1.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])

# convert 2D array to a 1D array without mentioning the actual size
flat_arr = np.reshape(arr, -1)
print('1D Numpy Array:')
print(flat_arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

numpy.reshape() returns a new view object if possible

With the help of reshape() function, we can view the input array and any modification done in the view object will be reflected in the original input too.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
[5, 3, 6],
[2, 9, 5]])
flat_arr = np.reshape(arr,-1)
print('1D Numpy Array:')
print(flat_arr)
# Modify the element at the first row and first column in the 1D array
arr[0][0] = 11
print('1D Numpy Array:')
print(flat_arr)
print('2D Numpy Array:')
print(arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

1D Numpy Array:
[11 4 2 5 3 6 2 9 5]

2D Numpy Array:

[[11 4 2]
[ 5 3 6]
[ 2 9 5]]

Convert 2D Numpy array to 1D array but Column Wise

If we pass the order parameter in reshape() function as “F” then it will read 2D input array column-wise. As we will show below-

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Read 2D array column by column and create 1D array from it
flat_arr = np.reshape(arr, -1, order='F')
print('1D Numpy Array:')
print(flat_arr)

Output:

1D Numpy Array:
[7 5 2 4 3 9 2 6 5]

Python: Convert Matrix / 2D Numpy Array to a 1D Numpy Array | How to make a 2d Array into a 1d Array in Python? Read More »

numpy.amin() Find minimum value in Numpy Array and it’s index

numpy.amin() | Find minimum value in Numpy Array and it’s index | Python Numpy amin() Function

In this tutorial, we have shared the numpy.amin() statistical function of the Numpy library with its syntax, parameters, and returned values along with a few code examples to aid you in understanding how this function works. Also, you can easily find the minimum value in Numpy Array and its index using Numpy.amin() with sample programs.

numpy.amin()

The numpy.amin() function returns minimum value of an array. Also, it is a statistical function of the NumPy library that is utilized to return the minimum element of an array or minimum element along an axis.

Syntax:

The syntax needed to use this function is as follows:

numpy.amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>)

In this, we will pass two arguments-

where

  • a: It is the array from where we have to find min value
  • axis: It is optional and if not provided then it will pass the NumPy array and returns the min value.
    • If it’s given then it will return for an array of min values along the axis i.e.
    • In the case of axis=0 then it returns an array containing min value for each column.
    • In the case of axis=1 then it returns an array containing min value for each row.

Parameters:

Now it’s time to explain the parameters of this method:

  • a: This parameter shows the input data that is in the form of an array.
  • axis: It is an optional parameter registering the Axis or axes along which to operate. The value of this parameter can be int or a tuple of int values and also has a default value as None.
  • out: This optional parameter is applied to show an alternative output array in which the result becomes stored. The value of this parameter is in the form of an ndarray.
  • keepdims: By this optional parameter(having boolean value), the result will broadcast perfectly against the input array. If this option is set to True, the axes which are overcome are left in the result as dimensions with size one.
  • initial: This is a scalar and optional parameter used to show the maximum value of an output element.
  • where: This is an optional parameter used to indicate the elements to compare for the value.

Return Value:

The minimum of an array – arr[ndarray or scalar], scalar if the axis is None; the result is an array of dimension a.ndim – 1 if the axis is mentioned.

Also Refer:

Example on NumPy amin() Function

a = np.arange(9).reshape((3,3))

print("The Array is :")
print(a)

print("Minimum element in the array is:",np.amin(a))         

print("Minimum element along the first axis of array is:",np.amin(a, axis=0))  

print("Minimum element along the second axis of array is:",np.amin(a, axis=1))

Output:

The Array is : [[0 1 2] [3 4 5] [6 7 8]]

Minimum element in the array is: 0

Minimum element along the first axis of array is: [0 1 2]

Minimum element along the second axis of array is: [0 3 6]

Find the minimum value in a 1D Numpy Array

So now we are going to use numpy.amin() to find out the minimum element from a 1D array.

import numpy
arr = numpy.array([11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17])
# Get the minimum element from a Numpy array
minElement = numpy.amin(arr)
print('Minimum element from Numpy Array : ', minElement)

Output:

Minimum element from Numpy Array : 11

Find minimum value & its index in a 2D Numpy Array

So here we are going to find out the min value in the 2D array.

import numpy
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16],
                     [17, 15, 11],
                     [12, 14, 15]])# Get the minimum element from a Numpy array
minElement = numpy.amin(arr2D)
print('Minimum element from Numpy Array : ', minElement)

Output:

Minimum element from Numpy Array : 11

Find min values along the axis in 2D numpy array | min in rows or columns:

If we pass axis=0 then it gives an array containing min of every column,

import numpy
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16],
                     [17, 15, 11],
                     [12, 14, 15]])
# Get the minimum values of each column i.e. along axis 0
minInColumns = numpy.amin(arr2D, axis=0)
print('min value of every column: ', minInColumns)

Output:

min value of every column: [11 12 11]

If we pass axis=1 then it gives an array containing min of every row,

import numpy 
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16], 
                      [17, 15, 11], 
                     [12, 14, 15]]) 
# Get the minimum values of each row i.e. along axis 1 
minInColumns = numpy.amin(arr2D, axis=1) 
print('min value of every column: ', minInColumns)

Output:

min value of every column: [11 14 11 12]

Find the index of minimum value from the 2D numpy array

So here we are going to discuss how to find out the axis and coordinate of the min value in the array.

import numpy
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16],
                     [17, 15, 11],
                     [12, 14, 15]])
result = numpy.where(arr2D == numpy.amin(arr2D))
print('Tuple of arrays returned : ', result)
print('List of coordinates of minimum value in Numpy array : ')
# zip the 2 arrays to get the exact coordinates
listOfCordinates = list(zip(result[0], result[1]))
# travese over the list of cordinates
for cord in listOfCordinates:
    print(cord)

Output:

Tuple of arrays returned : (array([0, 2], dtype=int32), array([0, 2], dtype=int32))
List of coordinates of minimum value in Numpy array :
(0, 0)
(2, 2)

numpy.amin() & NaN

if there is a NaN in the given numpy array then numpy.amin() will return NaN as minimum value.

import numpy
arr = numpy.array([11, 12, 13, 14, 15], dtype=float)
arr[3] = numpy.NaN
print('min element from Numpy Array : ', numpy.amin(arr))

Output:

min element from Numpy Array : nan

numpy.amin() | Find minimum value in Numpy Array and it’s index | Python Numpy amin() Function Read More »

Python-How to pad strings with zero, space or some other character

Python: How to pad strings with zero, space or some other character?

In this tutorial, we are going to discuss how to do padding of strings using zero, space, or some other character. Also, you can get complete knowledge of the methods used for padding strings in Python. So, let’s get started on learning How to pad strings with Zero, Space, or some other character.

Types of Padding in Python

There are two types of padding:

  1. Left padding
  2. Right padding

1. Left padding of string in Python

Left padding means adding a given character on the left side of a string.

For Example – If we pad three zeros in string 6 i.e, ‘0006’, or if we pad three space in string i.e,’6′

numStr = "6"
print('Original String :', numStr)
# Left pad the string with 0 to make it's length 4
numStr = numStr.zfill(4)
print('Updated String :' , numStr)

Output:

Original String : 6
Updated String : 0006

So in the above example, we have used'string.zfill(s, width)'to pad a given string on the left with zeros (0).

Also Check:

Left pad a string with space using string.rjust()

In this, we are going to use string.rjust() to add space in a given string.

numStr = "6"
print('Original String :', numStr)
# Make string right justified of length 4 by padding 3 spaces to left
numStr = numStr.rjust(4, ' ')
print('Updated String :', numStr)

Output:

Original String : 6
Updated String :    6

Left pad a string with some character using string.rjust()

For adding any character to our string we will use string.rjust() and pass that character in it.

numStr = "6"
print('Original String :', numStr)
# Make string right justified of length 4 by padding 3 '-' to left
numStr = numStr.rjust(4, '-')
print('Updated String :', numStr)

Output:

Original String : 6
Updated String : ---6

2. Right padding of string in Python

Right padding means adding a given character on the right side of the string.

Example- If we have a number string i.e. “ram”. Now we want to convert this string of length 3 to a string of length 6 by,

  • Right padding three zeros to the string i.e. “ram000”
  • Right padding three-space to the string i.e. “ram “
  • Right padding three characters to the string i.e. “ram—“

Right pad a string with zeros using string.ljust()

string.ljust() is used for padding a given character to the right of string to make its a length equal to the given width.

numStr = "67"
print('Original String :', numStr)
# Make string left justified of length 5 by padding 3 0s to the right of it
numStr = numStr.ljust(5, '0')
print('Updated String :', numStr)

Output:

Original String : 67
Updated String : 67000

Right pad a string with space using string.ljust()

In this, we will use string.ljust() to pad given character,

userName = "Shikha"
print('Original String :', userName)
# Make string left justified of length 7 by padding 3 spaces to the right of it
userName = userName.ljust(7, ' ')
print('Updated String :' , userName, 'is')

Here 3 spaces are padded to the right of the given string to make its length 9.

Output:

Original String : Shikha
Updated String : Shikha   is

Right pad a string with some character using string.ljust()

We can pass a character in string.ljust(s, width[, fillchar]) to right pad the given string by that passed character.

userName = "shikha"
print('Original String :', userName)
# Make string left justified of length 7 by padding 3 '-' to the right of it
userName = userName.ljust(7, '-')
print('Updated String :' , userName)

Output:

Here, three ‘-‘ are padded to the right of the given string to make its length 9.

Original String : shikha
Updated String : shikha---

Conclusion:

In this article, you have seen that how to do padding of strings using zero, space, or some other character.

Thank you!

Python: How to pad strings with zero, space or some other character? Read More »

Pandas : count rows in a dataframe | all or those only that satisfy a condition

Count all rows or those that satisfy some condition in Pandas dataframe

In this article we are going to show you how to count number of all rows in a DataFrame or rows that satisfy given condition in it.

First we are going to create dataframe,

import pandas as pd
students = [('Ankit', 22, 'Up', 'Geu'),
           ('Ankita', 31, 'Delhi', 'Gehu'),
           ('Rahul', 16, 'Tokyo', 'Abes'),
           ('Simran', 41, 'Delhi', 'Gehu'),
           ('Shaurya', 33, 'Delhi', 'Geu'),
           ('Harshita', 35, 'Mumbai', 'Bhu' ),
           ('Swapnil', 35, 'Mp', 'Geu'),
           ('Priya', 35, 'Uk', 'Geu'),
           ('Jeet', 35, 'Guj', 'Gehu'),
           ('Ananya', 35, 'Up', 'Bhu')
            ]
details = pd.DataFrame(students, columns =['Name', 'Age','Place', 'College'],
          index =['a', 'b', 'c', 'd', 'e','f', 'g', 'i', 'j', 'k'])

print(details)

Output:

RESTART: C:/Users/HP/Desktop/dataframe.py
Name       Age   Place      College
a   Ankit         22     Up          Geu
b   Ankita       31    Delhi       Gehu
c    Rahul       16    Tokyo      Abes
d   Simran     41     Delhi      Gehu
e   Shaurya    33     Delhi      Geu
f    Harshita   35     Mumbai Bhu
g   Swapnil    35     Mp        Geu
i    Priya         35     Uk         Geu
j    Jeet          35     Guj        Gehu
k   Ananya     35    Up         Bhu

Now lets see some other methods to count the rows in dataframe.

Count all rows in a Pandas Dataframe using Dataframe.shape

Dataframe.shape attribute gives a sequence of index or row labels

(Number_of_index, Number_of_columns)

Number of index basically means number of rows in the dataframe.Let’s use this to count number of rows in above created dataframe.

import pandas as pd
students = [('Ankit', 22, 'Up', 'Geu'),
           ('Ankita', 31, 'Delhi', 'Gehu'),
           ('Rahul', 16, 'Tokyo', 'Abes'),
           ('Simran', 41, 'Delhi', 'Gehu'),
           ('Shaurya', 33, 'Delhi', 'Geu'),
           ('Harshita', 35, 'Mumbai', 'Bhu' ),
           ('Swapnil', 35, 'Mp', 'Geu'),
           ('Priya', 35, 'Uk', 'Geu'),
           ('Jeet', 35, 'Guj', 'Gehu'),
           ('Ananya', 35, 'Up', 'Bhu')
            ]
details = pd.DataFrame(students, columns =['Name', 'Age','Place', 'College'],
          index =['a', 'b', 'c', 'd', 'e','f', 'g', 'i', 'j', 'k'])
numOfRows = details.shape[0]

print("Number of rows :",numOfRows)

Output:

RESTART: C:/Users/HP/Desktop/dataframe.py
Number of rows : 10

Count all rows in a Pandas Dataframe using Dataframe.index

Dataframe.index attribute gives a sequence of index or row labels.We can calculate the length of that sequence to find out the number of rows in the dataframe.

import pandas as pd
students = [('Ankit', 22, 'Up', 'Geu'),
           ('Ankita', 31, 'Delhi', 'Gehu'),
           ('Rahul', 16, 'Tokyo', 'Abes'),
           ('Simran', 41, 'Delhi', 'Gehu'),
           ('Shaurya', 33, 'Delhi', 'Geu'),
           ('Harshita', 35, 'Mumbai', 'Bhu' ),
           ('Swapnil', 35, 'Mp', 'Geu'),
           ('Priya', 35, 'Uk', 'Geu'),
           ('Jeet', 35, 'Guj', 'Gehu'),
           ('Ananya', 35, 'Up', 'Bhu')
            ]
details = pd.DataFrame(students, columns =['Name', 'Age','Place', 'College'],
          index =['a', 'b', 'c', 'd', 'e','f', 'g', 'i', 'j', 'k'])
numOfRows = len(details.index)
print('Number of Rows in dataframe : ' , numOfRows)

Output:

RESTART: C:/Users/HP/Desktop/dataframe.py

Number of rows : 10

Count rows in a Pandas Dataframe that satisfies a condition using Dataframe.apply()

This function apply  to all the rows of a dataframe to find out if elements of rows satisfies a condition or not, Based on the result it returns a bool series.

import pandas as pd
students = [('Ankit', 22, 'Up', 'Geu'),
           ('Ankita', 31, 'Delhi', 'Gehu'),
           ('Rahul', 16, 'Tokyo', 'Abes'),
           ('Simran', 41, 'Delhi', 'Gehu'),
           ('Shaurya', 33, 'Delhi', 'Geu'),
           ('Harshita', 35, 'Mumbai', 'Bhu' ),
           ('Swapnil', 35, 'Mp', 'Geu'),
           ('Priya', 35, 'Uk', 'Geu'),
           ('Jeet', 35, 'Guj', 'Gehu'),
           ('Ananya', 35, 'Up', 'Bhu')
            ]
details = pd.DataFrame(students, columns =['Name', 'Age','Place', 'College'],
          index =['a', 'b', 'c', 'd', 'e','f', 'g', 'i', 'j', 'k'])
seriesObj = details.apply(lambda x: True if x['Age'] > 30 else False , axis=1)
numOfRows = len(seriesObj[seriesObj == True].index)
print('Number of Rows in dataframe in which Age > 30 : ', numOfRows)

Output:

RESTART: C:/Users/HP/Desktop/dataframe.py
Number of Rows in dataframe in which Age > 30 : 8

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

Conclusion:

In this article we have seen different method to count rows in a dataframe  all or those  that satisfy a condition.

Happy learning guys.

Pandas : count rows in a dataframe | all or those only that satisfy a condition Read More »

Python Numpy : Select rows / columns by index from a 2D Numpy Array | Multi Dimension

Working with Numpy Arrays: Indexing

You have to be familiar with indexing if you want to work with Numpy arrays and matrices. You will use them when you would like to work with a subset of the array.

About 2d numpy array:

These dimentionals arrays are also known as matrices which can be shown as collection of rows and columns. In this article, we are going to show  2D array in Numpy in Python. NumPy is a very important library in python. We used NumPy for adding support for large multidimensional arrays & matrices .

Importing numpy module in your project:

import numpy as np

Indexing a Two-dimensional Array

import numpy as np
array1 = np.arange(12).reshape(4,3)
print(array1)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]

Here we use two indices,one we use for rows and one for column.Both the column and the row indices start from 0.

So in above all example we are going to use same matrices.

Select a single element from 2D Numpy Array by index

We can use [][] tese brackets to select an element from Numpy Array .

array1[row_index][column_index]

So if i want to access the element ‘10,’ we use the index ‘3’ for the row and index ‘1’ for the column.

import numpy as np
array1 = np.arange(12).reshape(4,3)
array1= array1[3][1]
print(array1)

Output:

RESTART: C:/Users/HP/Desktop/article2.py

10

Select Rows by Index from a 2D Numpy Array

We can use [] this bracket to select a single or multiple row. For single row use-

array1[row_index]

Let’s take an example,

import numpy as np
array1 = np.arange(12).reshape(4,3)
row = array1[1]
print(row)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[3 4 5]

For multiple rows use,

array1[start_index: end_index , :]

Let’s take an example,

import numpy as np
array1 = np.arange(12).reshape(4,3)
rows = array1[1:3, :]
print(rows)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[[3 4 5]
[6 7 8]]

Select Columns by Index from a 2D Numpy Array

Syntax for single column use,

array1[ : , column_index]

Lets take an example,

import numpy as np
array1 = np.arange(12).reshape(4,3)
column = array1[:, 1]
print(column)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[ 1 4 7 10]

Syntax to select multiple columns,

ndArray[ : , start_index: end_index]

Lets take an example,

import numpy as np
array1 = np.arange(12).reshape(4,3)
columns = array1[: , 1:3]
print(columns)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[[ 1 2]
[ 4 5]
[ 7 8]
[10 11]]

Select a Sub Matrix or 2d Numpy Array from another 2D Numpy Array

For sub 2d Numpy Array we pass the row & column index range in [] .

Syntax for this is,

ndArray[start_row_index : end_row_index , start_column_index : end_column_index]

lets take an example,

import numpy as np
array1 = np.arange(12).reshape(4,3)
sub2DArr = array1[1:3, 1:3]
print(sub2DArr)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[[4 5]
[7 8]]

Selected Row or Column or Sub Array is View only

This is for view only i.e. if there is  any modification in returned sub array will be reflected in original Numpy Array .

We are going to take same array which we have created in start of this article.

import numpy as np
array1 = np.arange(12).reshape(4,3)
row = array1[1]
print(row)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[3 4 5]

Now for any modification in the same row,

import numpy as np
array1 = np.arange(12).reshape(4,3)
row = array1[1]
row[:] = 20
print(row)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[20 20 20]

Modification in sub array will be shown in main Numpy Array too. Updated \ 2D Numpy Array array1 are,

[[ 0     1      2]
[20    20     20]
[ 6     7      8]
[ 9    10   11]]

Get a copy of 2D Sub Array from 2D Numpy Array using ndarray.copy()

Create a 2D Numpy array1 with3 rows & columns | Matrix

import numpy as np
array1 = np.array(([12, 22, 13], [21, 25, 30], [33, 17, 19]))
print(array1)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[[12 22 13]
[21 25 30]
[33 17 19]]

Select a copy of row at index 1 from 2D array and set all the elements in selected sub array to 20.

array1 = np.array(([12, 22, 13], [21, 25, 30], [33, 17, 19]))
row=array1[1].copy()
row[:] = 20
print(row)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
[20 20 20]

Conclusion:

So in this article we have seen how to work with NumPy arrays.Hope you have understood everything.

Python Numpy : Select rows / columns by index from a 2D Numpy Array | Multi Dimension Read More »

Python : How to use if, else and elif in Lambda Functions

Lambda function is the function that is anonymous. This anonymous functions are defined using a lambda keyword.

In this article we are going to  discuss about how to use if , else and elif in a lambda functions.

Syntax of Lambda function:

lambda arguments: expression

So this function can have any number of parameter but have only one expression.That expression should return.

Here is an example how we are using Lambda function:

# lambda.py

cube = lambda x: x * x * x

print(cube(11))

Output:

lambda.py

1331

How to use if-else in Lambda function:

Here we are going to use if-else in Lambda function.

lambda <arguments> : <Return Value if condition is True> if <condition> else <Return Value if condition is False>

Let’s take an example, Create  lambda function to check if the given value is between 11 to 22.

# lamda.py

verify = lambda x: True if (x > 9 and x < 18) else False
print(verify(5))
print(verify(17))
print(verify(21))

Output:

RESTART: C:/Users/HP/Desktop/lambda.py
False
True
False

 Conditional lambda function without if-else in python:

Without using if and else keyword we can still get our result using conditional lambda function.For example,

# lambda.py

verify = lambda x : x > 9 and x < 18
print(verify(5))
print(verify(17))
print(verify(21))

Output:

RESTART: C:/Users/HP/Desktop/lambda.py

False
True
False

So we have seen that we can get our result without using if-else statement.

Using filter() function with the conditional lambda function:

This function get a callback() function and a list of elements. It repeats over each and every elements in list and calls the callback() function on every element. If callback() returns True then it will add in new list .In the end, returns the list of items.

# lambda.py

listA = [12, 28, 23, 17, 9, 29, 50]

listOutput = list(filter(lambda x: x > 9 and x < 20, listA))
print(listOutput)

Output:

RESTART: C:/Users/HP/Desktop/lambda.py
[12, 17]

Here we have used lambda function to filter elements and in the end returns list of elements that lies between 9 to 20.

Using if, elif & else in a lambda function:

We can not always depend on if else in a lambda function,sometime there are some possibilities when we need to check on multiple conditions.We can’t directly use else if in a lambda function. But we can fo the same by using if else & brackets .

Syntax:

lambda <args> : <return Value> if <condition > ( <return value > if <condition> else <return value>)

Lets take an example:

lambda.py

converter = lambda x : x*2 if x < 11 else (x*3 if x < 22 else x)
print(converter(5))
print(converter(24))

Output:

lambda.py

10
24

So, in the above example, 5 * 2 = 10, which is less than 11. So, it gives10 because given condition is true. In the case of 24, condition is false; that is why it returns 24 as .

Conclusion:

So in this article we have seen how to use if , else and elif in a lambda functions.We have also seen how to use conditional statement and use of filter  in lambda function.

Python : How to use if, else and elif in Lambda Functions Read More »

Python : How to get Current date and time or timestamp ?

Timestamp is a order of characters or encrypted information point out when a certain event occurred, generally it gives date and time of day, sometimes exact to a small fraction of a second.

Get current timestamp using Python

So here we will show you various methods to find out latest date ,time or timestamp in Python.We will import functions from modules time, calendar and date.

1. Using module time :

The function time, return the time in seconds since the date & time as a floating point number.

#using time module
import time
  
# ts stores the time in seconds
ts = time.time()
  
# print the current timestamp
print(ts)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
1618989907.6277814

 

2. Using module datetime :

The datetime module arranges classes for manipulating dates and times. The function datetime.datetime.now which return number of seconds.

# using datetime module
import datetime;
  
# ct stores current time
ct = datetime.datetime.now()
print("current time:-", ct)
  
# ts store timestamp of current time
ts = ct.timestamp()
print("timestamp:-", ts)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
current time:- 2021-04-21 13:21:06.256878
timestamp:- 1618991466.25687

3. Using module calendar :

We are able to understand timestamp by combining multiple functions by multiple modules.

In this topic we are going to use function calendar.timegm to change tuple showing current time.

# using calendar module
# using time module
import calendar;
import time;
  
# gmt stores current gmtime
gmt = time.gmtime()
print("gmt:-", gmt)
  
# ts stores timestamp
ts = calendar.timegm(gmt)
print("timestamp:-", ts)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
gmt:- time.struct_time(tm_year=2021, tm_mon=4, tm_mday=21, tm_hour=8, tm_min=18, tm_sec=37, tm_wday=2, tm_yday=111, tm_isdst=0)
timestamp:- 1618993117

For Current Date only:

Let assume we do not want complete current timestamp, we  just want  current date only. Then what to do ?

datetime class consists of  2 other classes date & time . We can get date object from a datetime object.

from datetime import datetime 
dateTimeObj = datetime.now() 
dateObj = dateTimeObj.date()
print(dateObj)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
2021-04-21

For current Time only:

So here is the process if you want to know only current time.

As datetime module provides a datetime.time class too. We can get time object from a datetime object i.e.

from datetime import datetime
import time

dateTimeObj = datetime.now()
# get the time object from datetime object
timeObj = dateTimeObj.time()

print(timeObj)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
18:14:51.276231

For Current Timestamp using time.time():

Python gives us a module time & it also  has a function time() that returns the number of seconds.

from datetime import datetime
import time
dateTimeObj = datetime.now()
# get the time object from datetime object
timeObj = dateTimeObj.time()
secondsSinceEpoch = time.time()
timeObj = time.localtime(secondsSinceEpoch)
# get the current timestamp elements from struct_time object i.e.
print('Current TimeStamp is : %d-%d-%d %d:%d:%d' % (
timeObj.tm_mday, timeObj.tm_mon, timeObj.tm_year, timeObj.tm_hour, timeObj.tm_min, timeObj.tm_sec))

Output:

RESTART: C:/Users/HP/Desktop/article2.py
Current TimeStamp is : 21-4-2021 18:37:31

Get Current Timestamp using time.ctime():

Time module has some other function time.ctime() .

from datetime import datetime
import time
def ctime(seconds=None):
 timeStr = time.ctime()
 print('Current Timestamp : ', timeStr)
print(ctime())

Output:

RESTART: C:/Users/HP/Desktop/article2.py
Current Timestamp : Wed Apr 21 18:46:44 2021

Conclusion:

So In this article we have seen multiple ways to find out current Date & Time or Timestamp.We have also seen how to use ct.time() and time.time().

Python : How to get Current date and time or timestamp ? Read More »

Python GUI Programming With Tkinter

What Is A Graphical User Interface (GUI)?

Graphical User Interface (GUI) is nothing but a desktop application which helps you to interact with the computers. They perform different tasks in the desktops, laptops and other electronic devices.

  • GUI apps like Text-Editors create, read, update and delete different types of files.
  • Apps like Sudoku, Chess and Solitaire are games which you can play.
  • GUI apps like Google Chrome, Firefox and Microsoft Edge browse through the Internet.

They are some different types of GUI apps which we daily use on the laptops or desktops. We are going to learn how to create those type of apps.

Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.

What Is Tkinter?

Tkinter is actually an inbuilt Python module used to create simple GUI apps. It is the most commonly used module for GUI apps in the Python.

You don’t need to worry about installation of the Tkinter module as it comes with Python default.

To create a tkinter app:

  1. Importing the module – tkinter
  2. Create the main window (container)
  3. Add any number of widgets to the main window
  4. Apply the event Trigger on the widgets.

Importing tkinter is same as importing any other module in the Python code. Note that the name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.

import tkinter

There are two main methods used which the user needs to remember while creating the Python application with GUI.

1.Tk(screenName=None,  baseName=None,  className=’Tk’,  useTk=1):

To create a main window, tkinter offers a method ‘Tk(screenName=None,  baseName=None,  className=’Tk’,  useTk=1)’. To change the name of the window, you can change the className to the desired one. The basic code used to create the main window of the application is:

m=tkinter.Tk() where m is the name of the main window object

2.mainloop():

There is a method known by the name mainloop() is used when your application is ready to run. mainloop() is an infinite loop used to run the application, wait for an event to occur and process the event as long as the window is not closed.

m.mainloop()

Python-GUI-Programming-With-Tkinter_mainloop
Output:

 Python-GUI-Programming-With-Tkinter_mainloop-output

tkinter also offers access to the geometric configuration of the widgets which can organize the widgets in the parent windows. There are mainly three geometry manager classes class.

  1. pack() method:It organizes the widgets in blocks before placing in the parent widget.
  2. grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent widget.
  3. place() method:It organizes the widgets by placing them on specific positions directed by the programmer.

There are a number of widgets which you can put in your tkinter application. Some of the major widgets are explained below:

1.Button:

To add a button in your application, this widget is used.
The general syntax is:

w=Button(master, option=value)

master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the Buttons. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • activebackground: to set the background color when button is under the cursor.
  • activeforeground: to set the foreground color when button is under the cursor.
  • bg: to set he normal background color.
  • command: to call a function.
  • font: to set the font on the button label.
  • image: to set the image on the button.
  • width: to set the width of the button.
  • height: to set the height of the button.

Python-GUI-Programming-With-Tkinter_using-button
Output:

Python-GUI-Programming-With-Tkinter_using-button-output
2.Canvas:

It is used to draw pictures and other complex layout like graphics, text and widgets.
The general syntax is:

w = Canvas(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • bd: to set the border width in pixels.
  • bg: to set the normal background color.
  • cursor: to set the cursor used in the canvas.
  • highlightcolor: to set the color shown in the focus highlight.
  • width: to set the width of the widget.
  • height: to set the height of the widget.

 Python-GUI-Programming-With-Tkinter_using-canvas
Output:

 Python-GUI-Programming-With-Tkinter_canvas-output
3.CheckButton:

To select any number of options by displaying a number of options to a user as toggle buttons. The general syntax is:

w = CheckButton(master, option=value)

There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • Title: To set the title of the widget.
  • activebackground: to set the background color when widget is under the cursor.
  • activeforeground: to set the foreground color when widget is under the cursor.
  • bg: to set he normal backgrouSteganographyBreakSecret Code:Attach a File:nd color.
  • command: to call a function.
  • font: to set the font on the button label.
  • image: to set the image on the widget.

 Python-GUI-Programming-With-Tkinter_checkbutton.
Output:

Python-GUI-Programming-With-Tkinter_checkbutton-output
4.Entry:

It is used to input the single line text entry from the user.. For multi-line text input, Text widget is used.
The general syntax is:

w=Entry(master, option=value)

master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • bd: to set the border width in pixels.
  • bg: to set the normal background color.
  • cursor: to set the cursor used.
  • command: to call a function.
  • highlightcolor: to set the color shown in the focus highlight.
  • width: to set the width of the button.
  • height: to set the height of the button.

Python-GUI-Programming-With-Tkinter_using-entry
Output:

Python-GUI-Programming-With-Tkinter_using-entry-output
5.Frame:

It acts as a container to hold the widgets. It is used for grouping and organizing the widgets. The general syntax is:

w = Frame(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • highlightcolor: To set the color of the focus highlight when widget has to be focused.
  • bd: to set the border width in pixels.
  • bg: to set the normal background color.
  • cursor: to set the cursor used.
  • width: to set the width of the widget.
  • height: to set the height of the widget.

Python-GUI-Programming-With-Tkinter_frame.

Output:

Python-GUI-Programming-With-Tkinter_frame-output
6.Label:

It refers to the display box where you can put any text or image which can be updated any time as per the code.
The general syntax is:

w=Label(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • bg: to set he normal background color.
  • bg to set he normal background color.
  • command: to call a function.
  • font: to set the font on the button label.
  • image: to set the image on the button.
  • width: to set the width of the button.
  • height” to set the height of the button.

Python-GUI-Programming-With-Tkinter_label

Output:

 Python-GUI-Programming-With-Tkinter_label-output
7.Listbox:

It offers a list to the user from which the user can accept any number of options.
The general syntax is:

w = Listbox(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • highlightcolor: To set the color of the focus highlight when widget has to be focused.
  • bg: to set he normal background color.
  • bd: to set the border width in pixels.
  • font: to set the font on the button label.
  • image: to set the image on the widget.
  • width: to set the width of the widget.
  • height: to set the height of the widget.

 Python-GUI-Programming-With-Tkinter_listbox
Output:

 Python-GUI-Programming-With-Tkinter_listbox-output
8.MenuButton:

It is a part of top-down menu which stays on the window all the time. Every menubutton has its own functionality. The general syntax is:

w = MenuButton(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • activebackground: To set the background when mouse is over the widget.
  • activeforeground: To set the foreground when mouse is over the widget.
  • bg: to set he normal background color.
  • bd: to set the size of border around the indicator.
  • cursor: To appear the cursor when the mouse over the menubutton.
  • image: to set the image on the widget.
  • width: to set the width of the widget.
  • height: to set the height of the widget.
  • highlightcolor: To set the color of the focus highlight when widget has to be focused.

9.Menu:

It is used to create all kinds of menus used by the application.
The general syntax is:

w = Menu(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • title: To set the title of the widget.
  • activebackground: to set the background color when widget is under the cursor.
  • activeforeground: to set the foreground color when widget is under the cursor.
  • bg: to set he normal background color.
  • command: to call a function.
  • font: to set the font on the button label.
  • image: to set the image on the widget.

from tkinter import *
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label=’File’, menu=filemenu)
filemenu.add_command(label=’New’)
filemenu.add_command(label=’Open…’)
filemenu.add_separator()
filemenu.add_command(label=’Exit’, command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label=’Help’, menu=helpmenu)
helpmenu.add_command(label=’About’)
mainloop()
Output:
Menu output

10.Message:

It refers to the multi-line and non-editable text. It works same as that of Label.
The general syntax is:

w = Message(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • bd: to set the border around the indicator.
  • bg: to set he normal background color.
  • font: to set the font on the button label.
  • image: to set the image on the widget.
  • width: to set the width of the widget.
  • height: to set the height of the widget.

 

from tkinter import *
main = Tk()
ourMessage =’This is our Message’
messageVar = Message(main, text = ourMessage)
messageVar.config(bg=’lightgreen’)
messageVar.pack( )
main.mainloop( )
Output:
Python-GUI-Programming-With-Tkinter_message

11.RadioButton:

It is used to offer multi-choice option to the user. It offers several options to the user and the user has to choose one option.
The general syntax is:

w = RadioButton(master, option=value)

There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • activebackground: to set the background color when widget is under the cursor.
  • activeforeground: to set the foreground color when widget is under the cursor.
  • bg: to set he normal background color.
  • command: to call a function.
  • font: to set the font on the button label.
  • image: to set the image on the widget.
  • width: to set the width of the label in characters.
  • height: to set the height of the label in characters.
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text=’GfG’, variable=v, value=1).pack(anchor=W)
Radiobutton(root, text=’MIT’, variable=v, value=2).pack(anchor=W)
mainloop()

Output:

Radiobutton output
12.Scale:

It is used to provide a graphical slider that allows to select any value from that scale. The general syntax is:

w = Scale(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • cursor: To change the cursor pattern when the mouse is over the widget.
  • activebackground: To set the background of the widget when mouse is over the widget.
  • bg: to set he normal background color.
  • orient: Set it to HORIZONTAL or VERTICAL according to the requirement.
  • from_: To set the value of one end of the scale range.
  • to: To set the value of the other end of the scale range.
  • image: to set the image on the widget.
  • width: to set the width of the widget.
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()

Output:

Python-GUI-Programming-With-Tkinter_scale
13.Text: 

To edit a multi-line text and format the way it has to be displayed.
The general syntax is:

w  =Text(master, option=value)

There are number of options which are used to change the format of the text. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • highlightcolor: To set the color of the focus highlight when widget has to be focused.
  • insertbackground: To set the background of the widget.
  • bg: to set he normal background color.
  • font: to set the font on the button label.
  • image: to set the image on the widget.
  • width: to set the width of the widget.
  • height: to set the height of the widget.
from tkinter import *
root = Tk()
T = Text(root, height=2, width=30)
T.pack()
T.insert(END, ‘GeeksforGeeks\nBEST WEBSITE\n’)
mainloop()

Output:

Ttext output
14.TopLevel:

 This widget is directly controlled by the window manager. It don’t need any parent window to work on.The general syntax is:

w = TopLevel(master, option=value)

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • bg: to set he normal background color.
  • bd: to set the size of border around the indicator.
  • cursor: To appear the cursor when the mouse over the menubutton.
  • width: to set the width of the widget.
  • height: to set the height of the widget.

from tkinter import *
root = Tk()
root.title(‘GfG’)
top = Toplevel()
top.title(‘Python’)
top.mainloop()

Output:

Toplevel output

Conclusion:
In this tutorial, you learned how to get started with Python GUI programming. Tkinter is a compelling choice for a Python GUI framework because it’s built into the Python standard library, and it’s relatively painless to make applications with this framework.

Python GUI Programming With Tkinter Read More »