Python

Python: Check if all values are same in a Numpy Array (both 1D and 2D)

Checking if all the values are same in Numpy Array (both 1D and 2D) :

In this article we will discuss how we can check if all elements are same in 1D or 2D. We will also check if all rows or columns have same values or not.

Check if all elements are equal in a 1D Numpy Array using numpy.all() :

Here we compare all the elements with the first element of the array and returns a bool array of same size. If first element is equal to a element in main array, then true is returned else false is returned.

If all elements in bool array become true then all elements of main array are same.

import numpy as sc

# creating a 1D numpy array

num_arr = sc.array([14, 14, 14, 14, 14, 14])

# here we check if all values in array is same as first element

res = sc.all(num_arr == num_arr[0])

if res:

 print('All elements are same')

else:

 print('All elements are not same')
Output :
All elements are same

Check if all elements are equal in a 1D Numpy Array using min() & max() :

If maximum value of element is equal to minimum value of element in array then it indirectly means all values are same in the array.

import numpy as sc

# creating a 1D numpy array

num_arr = sc.array([14, 14, 14, 14, 14, 14])

# if min element= max element then all values in array are same

res = sc.max(num_arr) == sc.min(num_arr)

if res:

 print('All elements are equal')

else:

 print('All elements are not equal')
Output :
All elements are equal

Check if all elements are equal in a Multidimensional Numpy Array or Matrix :

We know that numpy.ravel() function returns flattened 1D view of a array. So we can easily convert a multi-dimensional flattened to 1D array and then compare first element with all the elements to check all element are same or not.

import numpy as sc

mul_arr = sc.array([[1, 1, 1],

[1, 1, 1],

[1, 1, 1]])

# to get a flattened 1D view of multidimensional numpy array

flatn_arr = sc.ravel(mul_arr)

# to check if all value in multidimensional array are equal

res = sc.all(mul_arr==flatn_arr[0])

if res:

 print('All elements are same')

else:

 print('All elements are not same')
Output :
All elements are same

Find rows or columns with same values in a matrix or 2D Numpy array :

Find rows with same values in a matrix or 2D Numpy array :

Similarly to check if all elements are same in each row, we can compare elements of each row with first element.

import numpy as sc
mul_arr = sc.array([[1, 1, 1],
[1, 21, 1],
[1, 1, 1]])
# to compare 1st element with elements of each row
for i in range(mul_arr.shape[0]):
 if sc.all(mul_arr[i]==mul_arr[i][0]):
  print('Row:', i)
print("Following rows have same elements")
Output :
Row: 0
Row: 2
Following rows have same elements

Find columns with same values in a matrix or 2D Numpy array :

Here also to check if all elements are same in each column, we can compare elements of each column with first element.

 

import numpy as sc
mul_arr = sc.array([[1, 1, 1],
[1, 21, 1],
[1, 1, 1]])
#to compare 1st element with elements of each row
trans_Arra = mul_arr.T
for i in range(trans_Arra.shape[0]):
 if sc.all(trans_Arra[i] == trans_Arra[i][0]):
  print('Column: ', i)
print("Following rows have same elements")
Output :
Column:  0
Column:  2
Following rows have same elements

Python: Check if all values are same in a Numpy Array (both 1D and 2D) Read More »

How to Reverse a 1D & 2D numpy array using np.flip() and [] operator in Python

Reversing a 1D and 2D numpy array using np.flip() and [] operator in Python.

Reverse 1D Numpy array using ‘[]’ operator :

By not passing any start or end parameter, so by default complete array is picked. And as step size is -1, so elements selected from last to first.

# Program :

import numpy as sc

# Creating a numpy array
num_arr = sc.array([11,22,33,44,55,66])

print('Original Array: ',num_arr)

# To get reverse of numpy array
rev_arr = num_arr[::-1]

print('Reversed Array : ', rev_arr)
Output :
Original Array:  [11 22 33 44 55 66]                                
Reversed Array :  [66 55 44 33 22 11]

Reverse Array is View Only :

Here if we do any modification in reversed array, it will also be reflected in original array.

# Program :

import numpy as sc

# Creatin a numpy array
num_arr = sc.array([11,22,33,44,55,66])

# To get reverse of numpy array
rev_arr = num_arr[::-1]
rev_arr[4]=63

print('Modified reversed Array : ', rev_arr)
print('Original array is: ',num_arr)
Output :
Modified reversed Array :  [66 55 44 33 63 11]                      
Original array is:  [11 63 33 44 55 66]

Reverse Numpy array using np.flip() :

flip() function provided by Python’s numpy module helps to flip or reverse the content of numpy array.

Syntax : numpy.flip(arr, axis=None)

where,

  • arr :  A numpy array
  • axis : Axis along which contents need to be flipped. If None, contents will be flipped along axis of array.

Reverse 1D Numpy array using np.flip() :

Here as it is 1 -D Numpy array, there is no need of axis parameter.

# Program :

import numpy as sc

# To create a Numpy array
num_arr = sc.array([11,22,33,44,55])

print('Original array: ',num_arr)

# To get reverse of numpy array
rev_arr = sc.flip(num_arr)

print('Reversed Array is : ', rev_arr)
Output :
Original array:  [11 22 33 44 55]
Reversed Array is :  [55 44 33 22 11]

Reverse 2D Numpy Array using np.flip() :

Reverse contents in all rows and all columns of 2D Numpy Array :

Here we don’t provide parameter in np.flip() function, then contents will be reversed along the axes of 2-D Numpy array.

# Program :

import numpy as sc

# to create a 2D Numpy array
twoD_Arr = sc.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print('Original Array is: ',twoD_Arr)

# to reverse 2D numpy array
rev_Arr = sc.flip(twoD_Arr)

print('Reversed Array : ')
print(rev_Arr)
Output :
Original Array is:
[[1 2 3]
[4 5 6]
[7 8 9]]
Reversed Array :
[[9 8 7]
[6 5 4]
[3 2 1]]

Reverse contents of all rows only in 2D Numpy Array :

If we provide axix parameter i.e. axis=1, then rows of array will be reversed.

# Program :

import numpy as sc

# to create a 2D Numpy array
twoD_Arr = sc.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print('Original Array is: ',twoD_Arr)

# to reverse the content of each row in array
rev_Arr = sc.flip(twoD_Arr, axis=1)

print('Reversed Array : ')
print(rev_Arr)
Output :
Original Array is:  [[1 2 3]
[4 5 6]
[7 8 9]]
Reversed Array :
[[3 2 1]
[6 5 4]
[9 8 7]]

Reverse contents of all columns only in 2D Numpy Array :

If we provide axix parameter i.e. axis=0, then rows of array will be reversed.

# Program :

import numpy as sc

# to create a 2D Numpy array
twoD_Arr = sc.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print('Original Array is: ',twoD_Arr)

# to reverse the content of each column in array
rev_Arr = sc.flip(twoD_Arr, axis=0)

print('Reversed Array : ')
print(rev_Arr)
Output :
Original Array is:
[[1 2 3]
[4 5 6]
[7 8 9]]
Reversed Array :
[[7 8 9]
[4 5 6]
[1 2 3]]

Reverse contents of only one row in 2D Numpy Array :

Let, we want to reverse only 1st row of a Numpy array.

# Program :

import numpy as sc

# to create a 2D Numpy array
twoD_Arr = sc.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print('Original Array is: ',twoD_Arr)

# to reverse only 1st row
twoD_Arr[0] = sc.flip(twoD_Arr[0])

print('Reversed Array : ')
print(twoD_Arr)
Output :
Original Array is:
[[1 2 3]
[4 5 6]
[7 8 9]]
Reversed Array :
[[3 2 1]
[4 5 6]
[7 8 9]]

Reverse contents of only one column in 2D Numpy Array :

Let, we want to reverse only 3rd column of a Numpy array.

# Program :

import numpy as sc

# to create a 2D Numpy array
twoD_Arr = sc.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print('Original Array is: ',twoD_Arr)

# to reverse the content of 3rd column in array
twoD_Arr[:,2] = sc.flip(twoD_Arr[:,2])

print('Reversed Array : ')
print(twoD_Arr)
Output :
Original Array is:
[[1 2 3]
[4 5 6]
[7 8 9]]
Reversed Array :
[[1 2 9]
[4 5 6]
[7 8 3]]

 

How to Reverse a 1D & 2D numpy array using np.flip() and [] operator in Python Read More »

Python : How to move files and Directories ?

How to move files and directories in python.

In python, shutil module offers various files related operations

Syntax- shutil.move(src, dst)

It accepts source and destination path and moves file or directory from source pointed as src to destination pointed as dst.

Move a file to an another directory :

 We will pass source file in first parameter and destination file in second parameter as string. Some points to keep in view.

  • If there is no file in destination directory then a new file will be created with the same name.
  • If already exists a file with same name in destination directory, then the file will be overwritten.
  • If in destination path, the path is not valid not existed it will result in FileNotFoundError.
import shutil
cre_path = shutil.move('satya.txt', 'document')    
print(cre_path)
Output :
FileNotFoundError: [Errno 2] No such file or directory: 'saya.txt'

Move a file with a new name :

 If we pass a new name of file in destination path, it will reflect in source file as it will move to source file with new name.

  • If there was already existed file with same name, then the file will be overwritten.
  • If path doesn’t exist for destination path it will result in error.

 

import shutil
cre_path = shutil.move('satya.txt', 'document/sample.txt')
print(cre_path)
Output :
FileNotFoundError: [Errno 2] No such file or directory: 'satya.txt'

Move all files in a directory to an another directory recursively :

Let there is a situation where we want move all the files form one directory to another directory. To implement this, using shtil.move(), we will iterate all files in source directory and move each file to destination directory.

import shutil,os,glob
def mov_every_Files_Dir(sourDir, destDir):
    print(sourDir)
    print(destDir)
    # checking if both the are directories are not
    if os.path.isdir(sourDir) and os.path.isdir(destDir) :
        # Iterate through all the files in source directory
        for filePath in glob.glob(sourDir + '/*'):
            # moving the files to destination directory
            print(file_path)
            shutil.move(file_path, destDir);
    else:
        print("srcDir & dstDir should be Directories")   
def main():        
    if __name__ == '__main__':
        main()
    srcDir = '/users/sjones/chem/notes'
    desDir =  '/users/sjones/chem/notes_backup'
    mov_every_Files_Dir(srcDir,desDir)

Move file and Create Intermediate directories :

                We know that if there is no directory in a given path, then shutil.move() will give error. So we will create a function which move the file to destination directory and also create all directories in given path.

import shutil, os, glob
def moven_cre_Dir(srcPath, destDir):
    if os.path.isdir(destDir) == False:
        os.makedirs(destDir); 
    shutil.move(srcPath, destDir);
def main():
    if __name__ == '__main__':
        main()
    moven_cre_Dir(srcDir, destDir)
    srcFile = 'certificate/document.txt'
    destDir =  'certificate/document9'

Move symbolic links :

If source file is a symbolic link, then a link will be created at destination path that will point to source link and subsequently source link will be deleted.

Move a directory to an another directory :

We can move an entire directory to other locations by keeping a view on some points.

import shutil
sour_dir = 'satya'
dest_dir =  'satya1'
shutil.move(sour_dir, dest_dir)
Output :
FileNotFoundError: [Errno 2] No such file or directory: 'satya'
  • If there was already a destination directory, then source directory will move to destination directory.
  • If destination directory is not there, then it will be created.
  • If there is no intermediate directory or path is invalid then there will be error.
  • If there is another directory with same name as that of the source in the destination directory, then there also will be error.

 

 

 

Python : How to move files and Directories ? Read More »

Python: How to delete specific lines in a file in a memory-efficient way?

How to delete specific lines in a file in a memory-efficient way ?

In this article, we will see how to delete a set of lines from a file in various ways.

We can not delete the lines from the file directly so we will first create a temporary file and write into it all the other lines. Then we will delete the original file and rename the temporary file.

We will be using the following file for demonstration

 File.txt

Line 1

Line 2

Line 3

Line 4

Line 5

Delete a line from a file by specific line number in python :

The algorithm will be-

  • Open the original file in reading mode
  • Enter the line number
  • Create a new temporary file and opening it in write mode
  • Read the contents of the file while keeping the count of the lines
    1. If the counter reaches the line we have to delete then skip this line
  • If any line was removed from the original file then delta the original file and rename the temporary file to that of the original file.
  • Else delete the temporary file.
import os
def deleteLine(originFile, lineNo):
    isSkipped = False
    index = 0
    tempFile = originFile + '.bak'
    #Open original file in read and temp file in write mode
    with open(originFile, 'r') as readObj, open(tempFile, 'w') as writeObj:
        #Copy all dat line by line
        for line in readObj:
            #When the loop counter is same as the line number skip
            if index != lineNo:
                writeObj.write(line)
            else:
                isSkipped = True
            index += 1
    #If any lines are not there rename temp as original file
    if isSkipped:
        os.remove(originFile)
        os.rename(tempFile, originFile)
    else:
        os.remove(tempFile)

#Line numbering starts from 0
deleteLine('file.txt',1)

After execution,

File.txt

Line 1

Line 3

Line 4

Line 5

Delete multiple lines from a file by line numbers :

The algorithm will be-

  • Open the original file in reading mode
  • Enter the line numbers to delete and pass it as a series
  • Create a new temporary file and opening it in write mode
  • Read the contents of the file while keeping the count of the lines
    1. If the counter reaches the numbers we have, then skip
  • If any line was removed from the original file then delta the original file and rename the temporary file to that of the original file.
  • Else delete the temporary file.
import os
def deleteLine(originFile, lineNo):
    isSkipped = False
    index = 0
    tempFile = originFile + '.bak'
    #Open original file in read and temp file in write mode
    with open(originFile, 'r') as readObj, open(tempFile, 'w') as writeObj:
        #Copy all dat line by line
        for line in readObj:
            #When the loop counter is same as the line number skip
            if index not in lineNo:
                writeObj.write(line)
            else:
                isSkipped = True
            index += 1
    #If any lines are not there rename temp as original file
    if isSkipped:
        os.remove(originFile)
        os.rename(tempFile, originFile)
    else:
        os.remove(tempFile)

#Line numbering starts from 0
deleteLine('file.txt',[0,2,3]

After execution,

file.txt

Line 2

Line 5 

Delete a specific line from the file by matching content :

The algorithm will be-

  • Open the original file in reading mode
  • Create a temporary file
  • Copy all contents from original file to the temp file line by line. If the line matches the lines we want to delete then skip
  • Compare both the files, if there are any difference delete original file and rename temp file as original.
import os
def deleteLine(originFile, lineToDelete):
    isSkipped = False
    tempFile = originFile + '.bak'
    #Open original file in read and temp file in write mode
    with open(originFile, 'r') as readObj, open(tempFile, 'w') as writeObj:
        #Copy all data line by line
        for line in readObj:
            currentLine = line
            if line[-1] == '\n':
                currentLine = line[:-1]
            # if currentLine matches with the given line then skip
            if currentLine != lineToDelete:
                writeObj.write(line)
    #If any lines are not there rename temp as original file
    if isSkipped:
        os.remove(originFile)
        os.rename(tempFile, originFile)
    else:
        os.remove(tempFile)

#Line numbering starts from 0
deleteLine('file.txt','Line 4')

After execution,

file.txt

Line 1

Line 2

Line 3

Line 5

Delete specific lines from a file that matches the given conditions :

The algorithm will be-

  • Accept the original file with a function as call-back.
  • Open the original file in reading mode
  • Enter the line numbers to delete and pass it as a series
  • Create a new temporary file and opening it in write mode
  • Read the contents of the file while keeping the count of the lines
    1. Pass each line into the function, if it returns true then skip
  • If any line was removed from the original file then deleted the original file and rename the temporary file to that of the original file.
  • Else delete the temporary file.
import os
def deleteLine(originFile, conditionalFunc):
    isSkipped = False
    tempFile = originFile + '.bak'
    #Open original file in read and temp file in write mode
    with open(originFile, 'r') as readObj, open(tempFile, 'w') as writeObj:
        #Copy all data line by line
        for line in readObj:
#Chech each file by passing it into the function
            if conditionalFunc(line) == False:
                writeObj.write(line)
    #If any lines are not there rename temp as original file
    if isSkipped:
        os.remove(originFile)
        os.rename(tempFile, originFile)
    else:
        os.remove(tempFile)

#Line numbering starts from 0
deleteLine('file.txt',conditionalFunction)

We can pass any function to check for our condition and when they are met, the lines are skipped.. The conditions can be anything like size of the line, line with a particular word in it etc.

Python: How to delete specific lines in a file in a memory-efficient way? Read More »

Python: String to datetime or date object

String to datetime or date object in Python.

We will see in this article how to convert different format string to a DateTime or date object. We will do so using a function provided by Python’s date-time module to change string into a datetime object i.e. strptime( )

Syntax-

datetime.strptime(datetime_str, format):

Arguments:

  • datetime_str – It takes the date and time information
  • format – The format in which we want the date item information based on which the object will be created

The function will return the  date time object when the right parameters are provided. In case there is something wrong with the parameters provided to the function will throw a value error.

Convert string (‘DD/MM/YY HH:MM:SS ‘) to datetime object :

We can obtain the date time in our desired format by passing in the correct format code as arguments.

  • %d – Days
  • %m – Month
  • %y – Years
  • %H – Hours
  • %M – Minutes
  • &S – Seconds
  • %z – Timezone
  • %f – Milliseconds
from datetime import datetime
dateTimeString = '15/5/21 11:12:13'
# Converting the String ( ‘DD/MM/YY HH:MM:SS ‘) into a datetime object
dateTimeObj = datetime.strptime(dateTimeString, '%d/%m/%y %H:%M:%S')
print(dateTimeObj)
Output :
2021-05-15 11:12:13

Convert string (‘MM/DD/YY HH:MM:SS ‘) to datetime object :

To achieve the ‘MM/DD/YY HH:MM:SS ‘ format we are goin to change the order of format from the previous code.

from datetime import datetime
dateTimeString = '5/15/2021 11:12:13'
#Converting the String ( ‘MM/DD/YY HH:MM:SS‘) into a datetime object
dateTimeObj = datetime.strptime(dateTimeString, '%m/%d/%Y %H:%M:%S')
print(dateTimeObj)
Output :
2021-05-15 11:12:13

Convert string to datetime and handle ValueError :

In case we pass a format that is not compatible with the with the function, it throws a ValueError.

We can handle that error beforehand so that the program execution does not stops.

(For correct format)

from datetime import datetime
dateTimeString = '5/15/2021 11:12:13'
#Converting the String ( ‘MM/DD/YY HH:MM:SS‘) into a datetime object
try:
    dateTimeObj = datetime.strptime(dateTimeString, '%m/%d/%Y %H:%M:%S')
    print(dateTimeObj)
except ValueError as e:
    print(e)
Output :
2021-05-15 11:12:13

(For wrong format)

from datetime import datetime
dateTimeString = '5/15/2021 11:12:13'
#Converting the String ( ‘MM/DD/YY HH:MM:SS‘) into a datetime object
try:
    dateTimeObj = datetime.strptime(dateTimeString, '%d-%m-%Y %H:%M:%S')
    print(dateTimeObj)
except ValueError as e:
    print(e)
Output :
time data '5/15/2021 11:12:13' does not match format '%d-%m-%Y %H:%M:%S'

Python: Convert string to datetime – ( string format yyyy-mm-dd hh-mm-ss) :

from datetime import datetime
dateTimeString = '2021-5-15 11-12-13'
#Converting the String ( ‘yyyy-mm-dd hh-mm-ss‘) into a datetime object
dateTimeObj = datetime.strptime(dateTimeString, '%Y-%m-%d %H-%M-%S')
print(dateTimeObj)
Output :
2021-05-15 11:12:13

Python: Convert string to datetime – ( string format MMM DD YYYY HH:MM:SS) :

from datetime import datetime
dateTimeString = 'May 15 2021 11:12:13'
#Converting the String ( ‘MMM DD YYYY HH:MM:SS‘) into a datetime object
dateTimeObj = datetime.strptime(dateTimeString, '%b %d %Y %H:%M:%S')
print(dateTimeObj)
Output :
2021-05-15 11:12:13

Python: Convert string to datetime with milliseconds- ( string format DD/MM/YY HH:MM:SS:FFFFFF) :

In case we have the millisecond info,

from datetime import datetime
dateTimeString = '15/5/21 11:12:13.453'
#Converting the String ( ‘DD/MM/YY HH:MM:SS:FFFFFF‘) into a datetime object
dateTimeObj = datetime.strptime(dateTimeString, '%d/%m/%y %H:%M:%S.%f')
print(dateTimeObj)
Output :
2021-05-15 11:12:13.453000

Python: Convert string to datetime with timezone :

To add the time zone in the format we have to include %z

from datetime import datetime
dateTimeString = '15/5/21 11:12:13+05:30'
#Converting the String wih timezone into a datetime object
dateTimeObj = datetime.strptime(dateTimeString, '%d/%m/%y %H:%M:%S%z')
print(dateTimeObj)
Output :
2021-05-15 11:12:13+05:30

Python: Convert string to date object :

To convert a datetime string into a date object we have to first convert it into a datetime object using strptime( ) and then pass it into the date( ) function to get our date object.

from datetime import datetime
dateTimeString = '2021-5-15'
#Converting the String into a date object
dateTimeObj = datetime.strptime(dateTimeString, '%Y-%m-%d').date()
print(dateTimeObj)
Output :
2021-05-15

Python: Convert string to time object :

To convert a datetime string into a time object we have to first convert it into a datetime object using strptime( ) and then pass it into the time( ) function to get our time object.

from datetime import datetime
dateTimeString = '11:12:13'
#Converting the String into a time object
dateTimeObj = datetime.strptime(dateTimeString, '%H:%M:%S').time()
print(dateTimeObj)
Output :
11:12:13

 

Python: String to datetime or date object Read More »

Python numpy.flatten() Function Tutorial with Examples

Python numpy.flatten() Function Tutorial with Examples | How to Use Function Numpy Flatten in Python?

In this tutorial, Beginners and Experience python developers will learn about function numpy.flatten(), how to use it, and how it works. Kindly, hit on the available links and understand how numpy.ndarray.flatten() function in Python gonna help you while programming.

numpy.ndarray.flatten() in Python

A numpy array has a member function to flatten its contents or convert an array of any shape to a 1D numpy array,

Syntax:

ndarray.flatten(order='C')

Parameters:

Here we can pass the following parameters-

Order: In this, we give an order in which items from the numpy array will be used,

C: Read items from array row-wise

F: Read items from array column-wise

A: Read items from array-based on memory order

Returns:

It returns a copy of the input array but in a 1D array.

Also Check:

Let’s learn the concept by viewing the below practical examples,

Flatten a matrix or a 2D array to a 1D array using ndarray.flatten()

First of all, import the numpy module,

import numpy as np

Let’s suppose, we have a 2D Numpy array,

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
print(arr_2d)

Output:

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

Now we are going to use the above 2D Numpy array to convert the 1D Numpy array.

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
print(arr_2d)
# Convert the 2D array to 1D array
flat_array = arr_2d.flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

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

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

So in the above example, you have seen how we converted the 2D array into a 1D array.

ndarray.flatten() returns a copy of the input array

flatten() function always returns a copy of the given array means if we make any changes in the returned array will not edit anything in the original one.

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
print(arr_2d)
flat_array = arr_2d.flatten()
flat_array[2] = 50
print('Flattened 1D Numpy Array:')
print(flat_array)
print('Original 2D Numpy Array')
print(arr_2d)

output:

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

Flattened 1D Numpy Array:
[ 7 4 50 5 4 3 9 7 1]

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

Thus in the above example, you can see that it has not affected the original array.

Flatten a 2D Numpy Array along Different Axis using flatten()

It accepts different parameter orders. It can be ‘C’ or ‘F’ or ‘A’, but the default value is ‘C’.
It tells the order.

  • C’: Read items from array row-wise i.e. using C-like index order.
  • ‘F’: Read items from array column-wise i.e. using Fortran-like index order.
  • ‘A’: Read items from an array on the basis of memory order of items.

In the below example, we are going to use the same 2D array which we used in the above example-

Flatten 2D array row-wise

In this, if we will not pass any parameter in function then it will take ‘C’ as a default value

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
flat_array = arr_2d.flatten(order='C')
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

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

Flatten 2D array column-wise

If we pass ‘F’ as the order parameter in  function then it means elements from a 2D array will be read column wise

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
flat_array = arr_2d.flatten(order='F')
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

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

Flatten 2D array based on memory layout

Let’s create a transparent view of the given 2D array

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
# Create a transpose view of array
trans_arr = arr_2d.T
print('Transpose view of array:')
print(trans_arr)

Output:

Transpose view of array:
[[7 5 9]
[4 4 7]
[2 3 1]]

Now flatten this view was Row Wise,

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
# Create a transpose view of array
trans_arr = arr_2d.T
flat_array = trans_arr.flatten(order='C')
print(flat_array )

Output:

[7 5 9 4 4 7 2 3 1]

Flatten a 3D array to a 1D numpy array using ndarray.flatten()

Let’s create a 3D numpy array,

import numpy as np

# Create a 3D Numpy array
arr = np.arange(12).reshape((2,3,2))
print('3D Numpy array:')
print(arr)

Output:

3D Numpy array:
[[[ 0 1]
[ 2 3]
[ 4 5]]

[[ 6 7]
[ 8 9]
[10 11]]]

Now we are going to flatten this 3D numpy array,

import numpy as np

# Create a 3D Numpy array
arr = np.arange(12).reshape((2,3,2))
# Convert 3D array to 1D
flat_array = arr.flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

Flattened 1D Numpy Array:
[ 0 1 2 3 4 5 6 7 8 9 10 11]

Flatten a list of arrays using numpy.ndarray.flatten()

Now, we have to create a list of arrays,

# Create a list of numpy arrays
arr = np.arange(5)
list_of_arr = [arr] * 5
print('Iterate over the list of a numpy array')
for elem in list_of_arr:
    print(elem)

Output:

Iterate over the list of a numpy array
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]

Now, its time to convert the above list of numpy arrays to a flat 1D numpy array,

# Convert a list of numpy arrays to a flat array
flat_array = np.array(list_of_arr).flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

Flattened 1D Numpy Array:
[0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]

Flatten a list of lists using ndarray.flatten()

To perform this process, first, we have to create a 2D numpy array from a list of list and then convert that to a flat 1D Numpy array,

# Create a list of list
list_of_lists = [[1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5]]
# Create a 2D numpy array from a list of list and flatten that array
flat_array = np.array(list_of_lists).flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)
# Convert the array to list
print('Flat List:')
print(list(flat_array))

Output:

Flattened 1D Numpy Array:
[1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5]
Flat List:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

Hence, this is how we can use flatten() function in numpy.

Conclusion:

We hope this python tutorial, you have seen how to use function numpy.flatten() assist you all in needy times. Thank you! keep visiting our site frequently for updated concepts of python.

Python numpy.flatten() Function Tutorial with Examples | How to Use Function Numpy Flatten in Python? Read More »

Python- Find indexes of an element in pandas dataframe

Python: Find indexes of an element in pandas dataframe | Python Pandas Index.get_loc()

In this tutorial, we will learn how to find the indexes of a row and column numbers using pandas in a dataframe. By learning from this tutorial, you can easily get a good grip on how to get row names in Pandas dataframe. Also, there is a possibility to learn about the Python Pandas Index.get_loc() function along with syntax, parameters, and a sample example program.

Pandas Index.get_loc() Function in Python

PandasIndex.get_loc()function results integer location, slice, or boolean mask for the requested label. The function acts with both sorted as well as unsorted Indexes. It gives various options if the passed value is not present in the Index.

Syntax:

Index.get_loc(key, method=None, tolerance=None)

Parameters:

  • key: label
  • method: {None, ‘pad’/’ffill’, ‘backfill’/’bfill’, ‘nearest’}, optional
  • default: exact matches only.
  • pad / ffill: If not having the exact match, find the PREVIOUS index value.
  • backfill / bfill: Utilize NEXT index value if no exact match
  • nearest: Make use of the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value.

Return Value:

loc : int if unique index, slice if monotonic index, else mask

Example using Index.get_loc() function:

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index(['Labrador', 'Beagle', 'Labrador',
                     'Lhasa', 'Husky', 'Beagle'])
  
# Print the Index
idx

Also View:

Creating a Dataframe in Python

The initial step is creating a dataframe.

Code:

# List of Tuples
empoyees = [('jack', 34, 'Sydney', 155),
            ('Riti', 31, 'Delhi', 177),
            ('Aadi', 16, 'Mumbai', 81),
            ('Mohit', 31, 'Delhi', 167),
            ('Veena', 81, 'Delhi', 144),
            ('Shaunak', 35, 'Mumbai', 135),
            ('Shaun', 35, 'Colombo', 111)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Marks'])
print(empDfObj)

Output:

Dataframe

Now, we want to find the location where the value ’81’ exists.

(4, 'Age')
(2, 'Marks')

We can see that value ’81’ exists at two different places in the data frame.

  1. At row index 4 & column “Age”
  2. At row index 2 & column “Marks”

Now, we will proceed to get the result of this.

Find all indexes of an item in pandas dataframe

Dataframe object and the value as an argument is accepted by the function we have created.

It returns the list of index positions at all occurrences.

Code:

def getIndexes(dfObj, value):
    ''' Get index positions of value in dataframe i.e. dfObj.'''
    listOfPos = list()
    # Get bool dataframe with True at positions where the given value exists
    result = dfObj.isin([value])
    # Get list of columns that contains the value
    seriesObj = result.any()
    columnNames = list(seriesObj[seriesObj == True].index)
    # Iterate over list of columns and fetch the rows indexes where value exists
    for col in columnNames:
        rows = list(result[col][result[col] == True].index)
        for row in rows:
            listOfPos.append((row, col))
    # Return a list of tuples indicating the positions of value in the dataframe
    return listOfPos

Output:

Find all indexes of an item in pandas dataframe

We got the exact row and column names of all the locations where the value ’81’ exists.

We will see what happened inside the getIndexes function.

How did it work?

Now, we will learn step by step process on what happened inside the getIndexes() function.

Step 1: Get bool dataframe with True at positions where the value is 81 in the dataframe using pandas.DataFrame.isin()

DataFrame.isin(self, values)

This isin() function accepts a value and returns a bool dataframe. The original size and the bool data frame size is the same. When the given value exists, it contains True otherwise False.

We will see the bool dataframe where the value is ’81’.

# Get bool dataframe with True at positions where value is 81
result = empDfObj.isin([81])
print('Bool Dataframe representing existence of value 81 as True')
print(result)

Output:

bool dataframe where the value is '81'

It is of the same size as empDfObj. As 81 exists at 2 places inside the dataframe, so this bool dataframe contains True at only those two places. In all other places, it contains False.

Step 2: Get the list of columns that contains the value

We will get the name of the columns that contain the value ’81’.We will achieve this by fetching names in a column in the bool dataframe which contains True value.

Code:

# Get list of columns that contains the value i.e. 81
seriesObj = result.any()
columnNames = list(seriesObj[seriesObj == True].index)

print('Names of columns which contains 81:', columnNames)

Output:

# Get list of columns that contains the value i.e. 81

Step 3: Iterate over selected columns and fetch the indexes of the rows which contains the value

We will iterate over each selected column and for each column, we will find the row which contains the True value.

Now these combinations of column names and row indexes where True exists are the index positions of 81 in the dataframe i.e.

Code:

# Iterate over each column and fetch the rows number where
for col in columnNames:
    rows = list(result[col][result[col] == True].index)
    for row in rows:
        print('Index : ', row, ' Col : ', col)

Output:

Iterate over selected columns and fetch the indexes of the rows which contains the value

Now it is clear that this is the way the getIndexes() function was working and finding the exact index positions of the given value & store each position as (row, column) tuple. In the end, it returns a list of tuples representing its index positions in the dataframe.

Find index positions of multiple elements in the DataFrame

Suppose we have multiple elements,

[81, 'Delhi', 'abc']

Now we want to find index positions of all these elements in our dataframe empDfObj, like this,

81  :  [(4, 'Age'), (2, 'Marks')]
Delhi  :  [(1, 'City'), (3, 'City'), (4, 'City')]
abc  :  []

Let’s use the getIndexes() and dictionary comprehension to find the indexes of all occurrences of multiple elements in the dataframe empDfObj.

listOfElems = [81, 'Delhi', 'abc']
# Use dict comprhension to club index positions of multiple elements in dataframe
dictOfPos = {elem: getIndexes(empDfObj, elem) for elem in listOfElems}
print('Position of given elements in Dataframe are : ')
for key, value in dictOfPos.items():
    print(key, ' : ', value)

Output:
getIndexes() and dictionary comprehension to find the indexes of all occurrences of multiple elements in the dataframe empDfObj.

dictOfPos is a dictionary of elements and their index positions in the dataframe. As ‘abc‘ doesn’t exist in the dataframe, therefore, its list is empty in dictionary dictOfPos.

Hope this article was understandable and easy for you!

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 – Find Elements in a Dataframe

Python: Find indexes of an element in pandas dataframe | Python Pandas Index.get_loc() Read More »

Python-How to append a new row to an existing csv file

Python: How to append a new row to an existing csv file?

This tutorial will help you learn how to append a new row to an existing CSV file using some CSV modules like reader/writer and the most famous DictReader/DictWriter classes. Moreover, you can also get enough knowledge on all python concepts by visiting our provided tutorials.

How to Append a new row to an existing csv file?

There are multiple ways in Python by which we can append rows into the CSV file. But here we will discuss two effective methods. Before going to learn those two methods, we have to follow the standard step which is explained ahead.

The basic step to proceed in this is to have a CSV file. For instance, here we have a CSV file named students.csv having the following contents:

Id,Name,Course,City,Session
21,Mark,Python,London,Morning
22,John,Python,Tokyo,Evening
23,Sam,Python,Paris,Morning

For reading and writing CSV files python provides a CSV module. There are two different classes for writing CSV files that is writer and DictWriter.

We can append the rows in a CSV file by either of them but some solutions are better than the other. We will see it in the next section.

Do Refer:

Append a list as a new row to an old CSV file using csv.writer()

A writer class is in the CSV module which writes the rows in existing CSV files.

Let’s take a list of strings:

# List of strings
row_contents = [32,'Shaun','Java','Tokyo','Morning']

To add this list to an existing CSV file, we have to follow certain steps:

  • Import CSV module’s writer class.
  • Open our csv file in append mode and create a file object.
  • Pass this file object to the csv.writer(), we can get a writer class object.
  • This writer object has a function writerow(), pass the list to it and it will add the list’s contents as a new row in the associated csv file.
  • A new row is added in the csv file, now close the file object.

By following the above steps, the list will be appended as a row in the CSV file as it is a simple process.

from csv import writer

def append_list_as_row(file_name, list_of_elem):
    # Open file in append mode
    with open(file_name, 'a+', newline='') as write_obj:
        # Create a writer object from csv module
        csv_writer = writer(write_obj)
        # Add contents of list as last row in the csv file
        csv_writer.writerow(list_of_elem)

Another Code:

Append a list as new row to an old csv file using csv.writer()

We can see that the list has been added.

Appending a row to csv with missing entries?

Suppose we have a list that does not contain all the values and we have to append it into the CSV file.

Suppose the list is:

list = [33, ‘Sahil’, ‘Morning’]

Example:

# A list with missing entries
row_contents = [33, 'Sahil', 'Morning']
# Appending a row to csv with missing entries
append_list_as_row('students.csv', row_contents)

some entries are missing in the list

Output:

output of missing files

We can see the data get appended at the wrong positions as the session got appended at the course.

csv’s writer class has no functionality to check if any of the intermediate column values are missing in the list or if they are in the correct order. It will just add the items in the list as column values of the last row in sequential order.

Therefore while adding a list as a row using csv.writer() we need to make sure that all elements are provided and are in the correct order.

If any element is missing like in the above example, then we should pass empty strings in the list like this,

row_contents = [33, 'Sahil', '' , '', 'Morning']

Since we have a huge amount of data in the CSV file, adding the empty strings in all of that will be a hectic task.

To save us from hectic work, the CSV provided us with the DictWriter class.

Append a dictionary as a row to an existing csv file using DictWriter in python

As the name suggests, we can append a dictionary as a row to an existing CSV file using DictWriter in Python. Let’s see how we can use them.

Suppose, we have a dictionary-like below,

{'Id': 81,'Name': 'Sachin','Course':'Maths','City':'Mumbai','Session':'Evening'}

We can see that the keys are the columns of the CSV and the values will be the ones we will provide.

To append it, we have to follow some steps given below:

  • import csv module’s DictWriter class,
  • Open our csv file in append mode and create a file object,
  • Pass the file object & a list of csv column names to the csv.DictWriter(), we can get a DictWriter class object
  • This DictWriter object has a function writerow() that accepts a dictionary. pass our dictionary to this function, it adds them as a new row in the associated csv file,
  • A new line is added in the csv file, now close the file object,

The above steps will append our dictionary as a new row in the csv. To make our life easier, we have created a separate function that performs the above steps,

Code:

from csv import DictWriter
def append_dict_as_row(file_name, dict_of_elem, field_names):
    # Open file in append mode
    with open(file_name, 'a+', newline='') as write_obj:
        # Create a writer object from csv module
        dict_writer = DictWriter(write_obj, fieldnames=field_names)
        # Add dictionary as wor in the csv
        dict_writer.writerow(dict_of_elem)

Append a dictionary as a row to an existing csv file using DictWriter in python

Output:

output of appending the dict

We can see that it added the row successfully. We can also consider this thought that what if our dictionary will have any missing entries? Or the items are in a different order?

The advantage of using DictWriter is that it will automatically handle the sort of things and columns with missing entries will remain empty. Let’s check an example:

field_names = ['Id','Name','Course','City','Session']
row_dict = {'Id': 81,'Name': 'Sachin','Course':'Maths','City':'Mumbai','Session':'Evening'}
# Append a dict as a row in csv file
append_dict_as_row('students.csv', row_dict, field_names)

Output:

column with missing entries will remain empty

We can see this module has its wonders.

Hope this article was useful and informative for you.

Python: How to append a new row to an existing csv file? Read More »

How to Check if a Directory is Empty

Python : How to Check if a Directory is Empty ?

One of Python’s many features is the ability to determine whether or not a directory is empty. The os module can be used to accomplish this. In Python, the OS module has functions for communicating with the operating system. Python’s basic utility modules include OS. This module allows you to use operating system-dependent features on the go. Many functions to communicate with the file system are included in the os and os.path modules.

A directory, also known as a folder, is a grouping of files and subdirectories. The os module in Python contains many useful methods for working with directories (and files as well).

Given a directory the task is to check whether the given _directory is empty or not

Check if a Directory is Empty

The os module in Python has a feature that returns a list of files or folders in a directory.

os.listdir(path='.')

It gives you a list of all the files and subdirectories in the direction you specified.

There are several ways to check whether the directory is empty or not some of them are:

Method #1:Using len() function

The directory is empty if the returned list is empty or has a size of 0.

We can find size using len() function.

If the given then it will print given_directory is empty else given_directory is not empty

Below is the implementation:

# checking if the given directory is empty or not
if len(os.listdir('/home/btechgeeks/posts')) == 0:
    print("given_directory is empty")
else:
    print("given_directory is not empty")

Output:

given_directory is empty

Method #2:Using not operator

If not of given path is true then it will print given_directory is empty

else given_directory is not empty.

Below is the implementation:

# checking if the given directory is empty or not
if not os.listdir('/home/btechgeeks/posts'):
    print("given_directory is empty")
else:
    print("given_directory is not empty")

Output:

given_directory is empty

In exceptional cases, check to see if a directory is empty

There may be times when os.listdir() throws an exception. As an example,

  • If the specified path does not exist.
  • If the given path exists, but it is not a directory.

In both cases, os.listdir() will return an error, so we must check this first before calling os.listdir().

Below is the implementation:

# checking if the given directory is empty or not
# given  directory
given_directory = '/home/btechgeeks/posts'
if os.path.exists(given_directory) and os.path.isdir(given_directory):
    if not os.listdir():
        print("given_directory is empty")
    else:
        print("given_directory is not empty")
else:
    print("given_directory doesn't exists')

Output:

given_directory is empty

Related Programs:

Python : How to Check if a Directory is Empty ? Read More »

Designing Code for Fibonacci Sequence without Recursion

Designing Code for Fibonacci Sequence without Recursion

Fibonacci sequence:

The Fibonacci sequence is a sequence type in which the sum of the previous two numbers is each consecutive number.

First few Fibonacci numbers are 0 1 1 2 3 5 8 …..etc.

Fibonacci sequence without recursion:

Let us now write code to display this sequence without recursion. Because recursion is simple, i.e. just use the concept,

Fib(i) = Fib(i-1) + Fib(i-2)

However, because of the repeated calculations in recursion, large numbers take a long time.

So, without recursion, let’s do it.

Approach:

  • Create two variables to hold the values of the previous and second previous numbers.
  • Set both variables to 0 to begin.
  • Begin a loop until N is reached, and for each i-th index
    • Print the sum of the previous and second most previous i.e sum= previous + second previous
    • Assign previous to second previous i.e. second previous= previous
    • Assign sum to previous i.e previous=sum

Below is the implementation:

1)C++ implementation of above approach.

#include <iostream>
using namespace std;
int main()
{ // given number
    int n = 10;
    // initializing previous and second previous to 0
    int previous = 0;
    int secondprevious = 0;
    int i;
    // loop till n
    for (i = 0; i < n; i++) {
        // initializing sum to previous + second previous
        int sum = previous + secondprevious;
        cout << sum << " ";
        if (!sum)
            previous = 1;
        secondprevious = previous;
        previous = sum;
    }
    return 0;
}

2)Python implementation of above approach.

# given number
n = 10
# initializing previous and second previous to 0
previous = 0
secondprevious = 0
# loop till n
for i in range(n):
    sum = previous + secondprevious
    print(sum, end=" ")
    if (not sum):
        previous = 1
    # initializing value to previous to second previous
    secondprevious = previous
    previous = sum

Output:

0 1 1 2 3 5 8 13 21 34

Related Programs:

Designing Code for Fibonacci Sequence without Recursion Read More »