Shikha Mishra

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
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!

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.

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 : 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 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 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.

Dictionaries in Python

Python Dictionary:

Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.Keys are unique within a dictionary while values may not be.

Creating a dictionary:

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.

Creating a dictionary

Output:

If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −

creating dictionary output
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}.

Using built-in function dict()

Output:

using built-in function dict() output

Nested Dictionary:

Using nested dictionary

Adding elements to a Dictionary:

In Python Dictionary, Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key values can also be added to an existing Dictionary.While adding a value, if the key value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary.

Adding elements to a Dictionary

Output:

 

Accessing elements from a Dictionary:

In order to access the items of a dictionary refer to its key name.Key can be used inside square brackets.

Accessing elements from a Dictionary

Accessing element of a nested dictionary:

In order to access the value of any key in nested dictionary, use indexing []

Accessing element of a nested dictionary

Delete Dictionary Elements:

ou can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −

Delete Dictionary Elements

Properties of Dictionary Keys:

Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.

There are two important points to remember about dictionary keys −

(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins.

(b)Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like [‘key’] is not allowed.

Conclusion:

In this tutorial, you covered the basic properties of the Python dictionary and learned how to access and manipulate dictionary data.

How to Convert a Python String to int

Convert Python String to Int:

To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers.

Below is the list of possible ways to convert an integer to string in python:

1. Using int() function:

Syntaxint(string)

Example:

Using int() function

Output:

Using int() function output
As a side note, to convert to float, we can use float() in python:

Example:

use float() in python

Output:

use float() in python output
2. Using float() function:

We first convert to float, then convert float to integer. Obviously the above method is better (directly convert to integer).

Syntax: float(string)

Example:

Using-float-function

Output:

Using float() function output

If you have a decimal integer represented as a string and you want to convert the Python string to an int, then you just follow the above method (pass the string to int()), which returns a decimal integer.But By default, int() assumes that the string argument represents a decimal integer. If, however, you pass a hexadecimal string to int(), then you’ll see a ValueError

For value error

The error message says that the string is not a valid decimal integer.

When you pass a string to int(), you can specify the number system that you’re using to represent the integer. The way to specify the number system is to use base:

Now, int() understands you are passing a hexadecimal string and expecting a decimal integer.

Conclusion:

This article is all about how to convert python string to int.All methods are clearly explained here. Now I hope you’re comfortable with the ins and outs of converting a Python string to an int.

How to Run a Python Script

Python is not just one of the leading programming languages, but also a top choice for dealing with big data and data science projects. The fact that it is among the easiest languages to learn makes the high-level, interpreted, general-purpose programming language even more lucrative.

For using Python on a system, the user first needs to install the Python environment. It will also install the Python interpreter, which is responsible for carrying out Python code execution. It is possible to run Python code directly from the terminal using the Python interpreter.

Python is a well known high-level programming language. The Python script is basically a file containing code written in Python. The file containing python script has the extension ‘.py’ or can also have the extension ‘.pyw’ if it is being run on a windows machine. To run a python script, we need a python interpreter that needs to be downloaded and installed.

Scripts vs Modules:

A Python script is a collection of commands in a file designed to be executed like a program. The file can of course contain functions and import various modules, but the idea is that it will be run or executed from the command line or from within a Python interactive shell to perform a specific task. Often a script first contains a set of function definitions and then has the main program that might call the functions.

Scripts are always processed by some kind of interpreter, which is responsible for executing each command sequentially.

A plain text file containing Python code that is intended to be directly executed by the user is usually called script, which is an informal term that means top-level program file.

On the other hand, a plain text file, which contains Python code that is designed to be imported and used from another Python file, is called module.

So, the main difference between a module and a script is that modules are meant to be imported, while scripts are made to be directly executed.

Different ways to run Python Script:

  1. Interactive Mode
  2. Command Line
  3. Text Editor
  4. IDE (PyCharm)

 

1.Interactive Mode:

Interactive mode, also known as the REPL provides us with a quick way of running blocks or a single line of Python code. The code executes via the Python shell, which comes with Python installation. Interactive mode is handy when you just want to execute basic Python commands or you are new to Python programming and just want to get your hands dirty with this beautiful language.

To access the Python shell, open the terminal of your operating system and then type “python”. Press the enter key and the Python shell will appear. This is the same Python executable you use to execute scripts, which comes installed by default on Mac and Unix-based operating systems.

How to Run a Python Script_interactive mode
The >>> indicates that the Python shell is ready to execute and send your commands to the Python interpreter. The result is immediately displayed on the Python shell as soon as the Python interpreter interprets the command.

To run your Python statements, just type them and hit the enter key. You will get the results immediately, unlike in script mode. For example, to print the text “Hello World”, we can type the following:

Interactive Mode output

2.Command Line:

To run a Python script store in a ‘.py’ file in command line, we have to write ‘python’ keyword before the file name in the command prompt.

python hello.py

You can write your own file name in place of ‘hello.py’.

Using command line
3.Text Editor :

Python’s standard distribution includes IDLE as the default IDE, and you can use it to write, debug, modify, and run your modules and scripts.

Other IDEs such as Eclipse-PyDev, PyCharm, Eric, and NetBeans also allow you to run Python scripts from inside the environment.

Advanced text editors like Sublime Text andVisual Studio Code also allow you to run your scripts.

4.IDE (PyCharm):

To run Python script on a IDE like PyCharm you will have to do the following:

  • Create a new project.
  • Give a name to that project as ‘NewProject’ and click on Create.
  • Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.
    Note: You don’t have to specify the extension as it will take it automatically.

Using IDE (PyCharm)
Now write the below Python script to print the message:

print('Hello World !')

Using IDE (PyCharm) output

Conclusion:

With the reading of this tutorial, you have acquired the knowledge and skills you need to be able to run Python scripts and code in several ways and in a variety of situations and development environments.