<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Satyabrata Jena, Author at Python Programs</title>
	<atom:link href="https://python-programs.com/author/satyabrata/feed/" rel="self" type="application/rss+xml" />
	<link>https://python-programs.com/author/satyabrata/</link>
	<description>Python Programs with Examples, How To Guides on Python</description>
	<lastBuildDate>Fri, 10 Nov 2023 06:47:28 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.5</generator>
<site xmlns="com-wordpress:feed-additions:1">196068054</site>	<item>
		<title>Append/ Add an element to Numpy Array in Python (3 Ways)</title>
		<link>https://python-programs.com/append-add-an-element-to-numpy-array-in-python/</link>
		
		<dc:creator><![CDATA[Satyabrata Jena]]></dc:creator>
		<pubDate>Sat, 04 Nov 2023 13:45:51 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8744</guid>

					<description><![CDATA[<p>Adding an element to Numpy Array in Python In this article we are going to discuss 3 different ways to add element to the numpy array. Let&#8217;s see one by one method. By using append() method By using concatenate() method By using insert() method Method-1 : By using append() method : In numpy module of [&#8230;]</p>
<p>The post <a href="https://python-programs.com/append-add-an-element-to-numpy-array-in-python/">Append/ Add an element to Numpy Array in Python (3 Ways)</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Adding an element to Numpy Array in Python</h2>
<p>In this article we are going to discuss 3 different ways to add element to the numpy array.</p>
<p>Let&#8217;s see one by one method.</p>
<ul>
<li><a href="#By_using_append()_method">By using append() method</a></li>
<li><a href="#By_using_concatenate()_method">By using concatenate() method</a></li>
<li><a href="#By_using_insert()_method">By using insert() method</a></li>
</ul>
<h3><a id="By_using_append()_method"></a>Method-1 : By using append() method :</h3>
<p>In numpy module of python there is a function <span style="color: #222222; font-family: monospace;"><span style="background-color: #e9ebec;">numpy.append() </span></span>which can be used to add an element. We need to pass the element as the argument of the function.</p>
<p>Let’s take a  example where an array is declared first and then we used the <code>append()</code> method to add more elements  to the array.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np
arr = np.array([12, 24, 36])
new_Arr = np.append (arr, [48,50,64])
print(‘ array : ’,arr)
print(‘result = : ’ ,new_Arr)
</pre>
<pre>Output :
array : [ 12  24  36 ]
result = : [ 12   24   36  48   50   64 ]</pre>
<p>We can also insert a column by the use of  append() method .</p>
<p>Let’s take an example below where we created a 2-Darray and we have to  insert two columns at a specific place.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np
arr1= np.array([[12, 24, 36], [48, 50, 64]])
arr2 = np.array([[7], [8]])
new_Array = np.append(arr1,arr2, axis = 1)
print(' array : ',arr1)
print(' result = : ', new_Array)
</pre>
<pre>Output :
array : [ [ 12  24  36  ]  
[ 48  50  64  ] ]
result  : [  [ 12  24  36  7  ] 
[48  50  64   8  ]  ]</pre>
<p>We can also insert a row  by the use of  append() method.</p>
<p>Let’s take the  example below where we created a 2-D array and we have to  inserte  a row to it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np 
arr= np.array([[12, 24, 36], [48, 50, 62]])
new_Array = np.append(arr, [[70 ,80 ,90 ]], axis = 0)
print('array = ', arr )
print('result = ' ,new_Array)
</pre>
<pre>Output :
array = [ [ 12  24   36   ]  
[ 48  50    64   ] ]
result = [  [ 12   24   36   ] 
[ 48   50  64   ]
[70   80   90 ] ]</pre>
<h3><a id="By_using_concatenate()_method"></a>Method-2 : By using concatenate() method :</h3>
<p>In numpy module of python there is a function <code>numpy.concatenate()</code> to join two or more arrays. To add a single element we need to encapsulate the single value in a sequence data structure like list pass it to the function.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Numpy Array of integers created
arr = np.array([1, 2, 6, 8, 7])
# Adding an element at the end of a numpy array
new_arr = np.concatenate( (arr, [20] ) )
print('array: ', new_arr)
print('result: ', arr)</pre>
<pre>Output :
array:[1, 2, 6, 8, 7]
result: [1, 2, 6, 8, 7,20]</pre>
<p>Adding another array, see the below program</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np 
arr1 = np.array([[10, 20], [30, 40]])
arr2 = np.array([[50, 60]])
new_Array= np.concatenate((arr1,arr2 ), axis=0)
print( 'First Array : ' ,arr1 )
print( 'Second Array : ' , arr2  )
print( 'concatenated Array : ' , new_Array )
</pre>
<pre>Output :
First Array :   [[ 10  20 ]
                     [30  40 ]]
Second Array :  [[ 50  60 ] ]
 Concatenated Array :     [[ 10   20 ]
                                        [ 30   40 ]
                                        [ 50    60 ]]</pre>
<h3><a id="By_using_insert()_method"></a>Method-3 : By using insert() method :</h3>
<p>In numpy module of python there is a function <code>numpy.insert()</code> to add an element at the end of the numpy array.</p>
<p>Below program is to add an elements to the array.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np 
arr= np.array (  [ 16, 33, 47, 59, 63 ,79 ])
# Here specified at index 1, so elemnt will eb replaced with new element
new_Array = np.insert(arr, 1, 20 )
print('The array : ', arr)
print ('result :',  new_Array)
</pre>
<pre>Output :
array : [ 16  33  47  59  63  79 ]
result : [ 16  20  33  47  59  66  79 ]</pre>
<p>The post <a href="https://python-programs.com/append-add-an-element-to-numpy-array-in-python/">Append/ Add an element to Numpy Array in Python (3 Ways)</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8744</post-id>	</item>
		<item>
		<title>np.ones() – Create 1D / 2D Numpy Array filled with ones (1’s)</title>
		<link>https://python-programs.com/np-ones-create-1d-2d-numpy-array-filled-with-ones-1s/</link>
		
		<dc:creator><![CDATA[Satyabrata Jena]]></dc:creator>
		<pubDate>Fri, 03 Nov 2023 02:46:52 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=7834</guid>

					<description><![CDATA[<p>Create a 1D / 2D Numpy Arrays of zeros or ones In this article, we will learn to create array of various shapes where all the values are initialized with 0 &#38; 1. numpy.zeros() : A function is provided by Python&#8217;s numpy module i.e. numpy.zeros() which will create a numpy array of given shape and [&#8230;]</p>
<p>The post <a href="https://python-programs.com/np-ones-create-1d-2d-numpy-array-filled-with-ones-1s/">np.ones() – Create 1D / 2D Numpy Array filled with ones (1’s)</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Create a 1D / 2D Numpy Arrays of zeros or ones</h2>
<p>In this article, we will learn to create array of various shapes where all the values are initialized with 0 &amp; 1.</p>
<h3>numpy.zeros() :</h3>
<p>A function is provided by Python&#8217;s numpy module i.e. <code>numpy.zeros()</code> which will create a numpy array of given shape and where all values are initialized with 0&#8217;s.</p>
<p>i.e.</p>
<pre>numpy.zeros(shape, dtype=float, order='C')</pre>
<p>Arguments:-</p>
<ul>
<li><strong>shape</strong> : It denotes shape of the numpy array. It may be single int or sequence of int.</li>
<li><strong>dtype</strong> : It denotes data type of elements. Default value for dtype is float64.</li>
<li><strong>order</strong> : It denotes the order in which data is stored in a multi-dimension array. It is of two types</li>
</ul>
<ol>
<li>&#8216;F&#8217;: Data will be stored Row major order</li>
<li>&#8216;C&#8217;: Data will be stored in Column major order. Default value of <em>order </em>is &#8216;C&#8217;.</li>
</ol>
<p>Let&#8217;s see the below 4 different types implementation with code</p>
<ul>
<li style="list-style-type: none;">
<ul>
<li style="list-style-type: none;">
<ul>
<li><a href="#Creating_a_flattened_1D_numpy_array_filled_with_all_zeros">Creating a flattened 1D numpy array filled with all zeros</a></li>
<li><a href="#Creating_a_2D_numpy_array_with_4_rows_&amp;_3_columns,_filled_with_0’s">Creating a 2D numpy array with 4 rows &amp; 3 columns, filled with 0’s</a></li>
<li><a href="#Creating_a_flattened_1D_numpy_array_filled_with_all_Ones">Creating a flattened 1D numpy array filled with all Ones</a></li>
<li><a href="#Creating_a_2D_numpy_array_with_3_rows_&amp;_3_columns,_filled_with_1’s">Creating a 2D numpy array with 3 rows &amp; 3 columns, filled with 1’s</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h3><a id="Creating_a_flattened_1D_numpy_array_filled_with_all_zeros"></a>Creating a flattened 1D numpy array filled with all zeros :</h3>
<p>We can create a flattened numpy array with all values as &#8216;0&#8217;.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as sc
# create a 1D numpy array with values as 0
numarr = sc.zeros(5)
print('Contents of the Flattened Numpy Array : ')
print(numarr)
</pre>
<pre>Output :
Contents of the Flattened Numpy Array :
[0. 0. 0. 0. 0.]</pre>
<h3><a id="Creating_a_2D_numpy_array_with_4_rows_&amp;_3_columns,_filled_with_0’s"></a>Creating a 2D numpy array with 4 rows &amp; 3 columns, filled with 0’s :</h3>
<p>We can create a 2D numpy array by passing (4,3) as argument in <code>numpy.zeros()</code> which will return all values as &#8216;0&#8217;.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as sc
# create a 2D numpy array with values as 0 
numarr = sc.zeros((4,3))
print('Contents of the 2D Numpy Array : ')
print(numarr)
</pre>
<pre>Output :
Contents of the 2D Numpy Array :
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]</pre>
<p>We know that default value of dtype is float64, let&#8217;s try to change the dtype to int64.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as sc
# create a 2D numpy array with values as 0 which are of int data type
numarr = sc.zeros((4,3), dtype=sc.int64)
print('Contents of the 2D Numpy Array : ')
print(numarr)
</pre>
<pre>Output :
Contents of the 2D Numpy Array :
[[0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]]</pre>
<h3>numpy.ones() :</h3>
<p>A function is provided by Python&#8217;s numpy module i.e. <code>numpy.ones()</code> which will create a numpy array of given shape and where all values are initialized with 1&#8217;s.</p>
<p>i.e.</p>
<pre>numpy.ones(shape, dtype=float, order='C')</pre>
<p>Arguments:-</p>
<ul>
<li>shape : It denotes shape of the numpy array. It may be single int or sequence of int.</li>
<li>dtype : It denotes data type of elements. Default value for dtype is float64.</li>
<li>order : It denotes the order in which data is stored in a multi-dimension array. It is of two types</li>
</ul>
<ol>
<li>&#8216;F&#8217;: Data will be stored Row major order</li>
<li>&#8216;C&#8217;: Data will be stored in Column major order. Default value of <em>order </em>is &#8216;C&#8217;.</li>
</ol>
<h3><a id="Creating_a_flattened_1D_numpy_array_filled_with_all_Ones"></a>Creating a flattened 1D numpy array filled with all Ones :</h3>
<p>We can make all values as 1 in a flattened array.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as sc
# create a flattened 1D numpy array of size 5 where all values are 1
numarr = sc.ones(5)
print('Contents of the Flattened Numpy Array : ')
print(numarr)
</pre>
<pre>Output :
Contents of the Flattened Numpy Array :
[ 1.  1.  1.  1.  1.]</pre>
<h3><a id="Creating_a_2D_numpy_array_with_3_rows_&amp;_3_columns,_filled_with_1’s"></a>Creating a 2D numpy array with 3 rows &amp; 3 columns, filled with 1’s  :</h3>
<p>We can create a 2D numpy array by passing row and column as argument in <code>numpy.ones()</code> where all the values are 1.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as sc
# create a 2D numpy array with 3 rows &amp; 4 columns with all values as 1
numarr = sc.ones((3,3))
print('Contents of the 2D Numpy Array : ')
print(numarr)
print('Data Type of the contents in  given Array : ',numarr.dtype)
</pre>
<pre>Output :
Contents of the 2D Numpy Array :
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
Data Type of the contents in  given Array :  float64</pre>
<p>We know default type of dtype is float64, let&#8217;s try to change it to int64.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as sc
# create a 2D numpy array with values as 1 which are of int data type
numarr = sc.ones((4,3), dtype=sc.int64)
print('Contents of the 2D Numpy Array : ')
print(numarr)
</pre>
<pre>Output :
Contents of the 2D Numpy Array :
[[1 1 1]
 [1 1 1]
 [1 1 1]
 [1 1 1]]</pre>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/np-ones-create-1d-2d-numpy-array-filled-with-ones-1s/">np.ones() – Create 1D / 2D Numpy Array filled with ones (1’s)</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">7834</post-id>	</item>
		<item>
		<title>Python: How to insert lines at the top of a file?</title>
		<link>https://python-programs.com/python-how-to-insert-lines-at-the-top-of-a-file/</link>
		
		<dc:creator><![CDATA[Satyabrata Jena]]></dc:creator>
		<pubDate>Fri, 03 Nov 2023 02:46:28 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=7779</guid>

					<description><![CDATA[<p>Inserting lines at the top of a file Python: How to insert lines at the top of a file ? In this article, we will learn to insert single or multiple lines at the beginning of text file in python. Let&#8217;s see inserting a line at the top of a file : We can&#8217;t insert [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-how-to-insert-lines-at-the-top-of-a-file/">Python: How to insert lines at the top of a file?</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Inserting lines at the top of a file</h2>
<h3>Python: How to insert lines at the top of a file ?</h3>
<p>In this article, we will learn to insert single or multiple lines at the beginning of text file in python.</p>
<h3>Let&#8217;s see inserting a line at the top of a file :</h3>
<p>We can&#8217;t insert a text directly anywhere in a file. To insert a line of text at the top, we can create a new file with same name as that of the original file and with same line of text at the top. We can implement this by taking a function.</p>
<p>How the function works?</p>
<ul>
<li>First it accepts0 file path and new line that would be inserted as arguments</li>
<li>Then it creates &amp; then open a new temporary file in write mode.</li>
<li>After creating Temporary file then add the new line that you want to insert in beginning in temporary file</li>
<li>After this open the original file in read mode and read the contents line by line</li>
<li>&#8211; For each line add/append that into the temporary file</li>
<li>After appending contents and new line to the temporary new file, delete the original file.</li>
<li>At last, rename the temporary new file as that of the original file.</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import os
def prepend_singline(filename, line):
    # Code to insert new line at the beginning of a file
    # define a name to temporary file
    tempfile = filename + '.abc'
    # Open the available original file in read mode and temporary file in write mode
    with open(filename, 'r') as read_objc, open(tempfile, 'w') as write_objc:
        # Write new line to the temporary file
        write_objc.write(line + '\n')
        # Read lines from the original file and append them to the temporary file
        for line in read_obj:
            write_objc.write(line)
    # delete original file
    os.remove(filename)
    # Rename temporary file as that of the original file
    os.rename(tempfile, filename)
def main():
    # Insert new line before the first line of original file
    prepend_singline("document.txt", "This is a new line")
if __name__ == '__main__':
   main() 
</pre>
<pre>Output :
This is a new line
Hi, welcome to document file
 India is my country
Content Line I
Content Line II
This is the end of document file</pre>
<h3>Insert multiple lines at the top of a file :</h3>
<p>Let we have a list of strings and we want to add these to the beginning of a file. Rather than calling above used function and adding new line one by one to new file, we can create another function which accepts file name and list of strings as arguments.</p>
<p>Then we can add list of strings in the beginning of temporary new file by adding lines from list of strings and contents to new file and renaming the new file as the original one.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import os
def prepend_multlines(filename, list_asmult_lines):
    """Code to insert new list of string at beginning of a file"""
    # define a name to temporary file
    dummyfile = filename + '.abc'
    # Open the available original file in read mode and temporary file in write mode
    with open(filename, 'r') as read_objc, open(dummyfile, 'w') as write_objc:
        # Iterate over the given list of strings and write them to dummy file as lines
        for line in list_of_lines:
            write_obj.write(line + '\n')
        # Read lines one by one from the original file and append them to the temporary file
        for line in read_objc:
            write_objc.write(line)
    # delete original file
    os.remove(filename)
    # Rename temporary file as that of the original file
    os.rename(dummyfile, filename)
def main():
    list_asmult_lines = ['New Line A', 'New Line B',  'New Line C']
    # Insert string list as new line before the first line of original file
    prepend_multlines("document.txt", list_asmult_lines)
if __name__ == '__main__':
   main()    
</pre>
<pre>Output :
New Line A
New Line B
New Line C
Hi, welcome to document file
 India is my country
Content Line I
Content Line II
This is the end of document file</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/python-how-to-insert-lines-at-the-top-of-a-file/">Python: How to insert lines at the top of a file?</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">7779</post-id>	</item>
		<item>
		<title>How to check if a file or directory or link exists in Python ?</title>
		<link>https://python-programs.com/how-to-check-if-a-file-or-directory-or-link-exists-in-python/</link>
		
		<dc:creator><![CDATA[Satyabrata Jena]]></dc:creator>
		<pubDate>Fri, 03 Nov 2023 02:46:25 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=7741</guid>

					<description><![CDATA[<p>Checking if a file or directory or link exists in Python In this article, we are going to see how to check if a file, directory or a link exists using python. Let&#8217;s see one by one Check if a path exists Check if a file exists Check if a Directory exists Check if given [&#8230;]</p>
<p>The post <a href="https://python-programs.com/how-to-check-if-a-file-or-directory-or-link-exists-in-python/">How to check if a file or directory or link exists in Python ?</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Checking if a file or directory or link exists in Python</h2>
<p>In this article, we are going to see how to check if a file, directory or a link exists using python.</p>
<p>Let&#8217;s see one by one</p>
<ul>
<li><a href="#Check_if_a_path_exists">Check if a path exists</a></li>
<li><a href="#Check_if_a_file_exists">Check if a file exists</a></li>
<li><a href="#Check_if_a_Directory_exists">Check if a Directory exists</a></li>
<li><a href="#Check_if_given_path_is_a_link">Check if given path is a link</a></li>
</ul>
<h3><a id="Check_if_a_path_exists"></a>Python – Check if a path exists :</h3>
<pre>Syntax- os.path.exists(path)</pre>
<p>The above function will return true if the path exists and false if it does not. It can take either relative or absolute path as parameter into the function.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import os

pathString = "E:\Python"

# Check for path existence
if os.path.exists(pathString):
    print("Path Exists!")
else:
    print("Path could not be reached")
</pre>
<pre>Output :
Path Exists!</pre>
<p>However we should ensure that we have sufficient user rights available to access the path.</p>
<h3><a id="Check_if_a_file_exists"></a>Python – Check if a file exists :</h3>
<p>While accessing files inside python, if the file does not exist beforehand, we will get a <em><code>FileNotFoundError</code>. </em>To avoid these errors we should always check if a particular file exists. For that we would have to use the following function</p>
<pre>Syntax- os.path.isfile(path)</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import os

filePathString = "E:\Python\data.csv"

# Check for file existence
if os.path.isfile(filePathString):
    #If the file exists display its contents
    print("File Exists!")
    fileHandler = open(filePathString, "r")
    fileData = fileHandler.read()
    fileHandler.close()
    print(fileData)
else:
    print("File could not be found")
</pre>
<pre>Output :
File Exists!
Id,Name,Course,City,Session
21,Jill,DSA,Texas,Night
22,Rachel,DSA,Tokyo,Day
23,Kirti,ML,Paris,Day
32,Veena,DSA,New York,Night</pre>
<h3><a id="Check_if_a_Directory_exists"></a>Python – Check if a Directory exists :</h3>
<p>To check if a given directory exists or not, we can use the following function</p>
<pre>Syntax- os.path.isdir(path)</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import os

filePathString = "E:\Python\.vscode"

# Check for directories existence
if os.path.isdir(filePathString):
    # If the directory exists display its name
    print(filePathString, "does exist")
else:
    print("Directory could not be found")
</pre>
<pre>Output :
.vscode does exist</pre>
<h3><a id="Check_if_given_path_is_a_link"></a>Python – Check if given path is a link :</h3>
<p>We can use <code>isdir( )</code> and <code>isfile( )</code> to check if a symbolic(not broken) link exists. For that we have a dedicated function in os module</p>
<pre>Syntax- os.path.islink(path)</pre>
<p>We will be using <code>path.exists</code> and <code>path.islink</code> together in this function so that we can check if the link exists and if it is intact.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import os

linkPathString = "E:\Python\data.csv"

# Check for link
if os.path.exists(linkPathString) and os.path.islink(linkPathString):
    print("The link is present and not broken")
else:
    print("Link could not be found or is broken")
</pre>
<pre>Output :
Link could not be found or is broken</pre>
<p>As the path we provided is not a link, the program returns the else condition.</p>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/how-to-check-if-a-file-or-directory-or-link-exists-in-python/">How to check if a file or directory or link exists in Python ?</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">7741</post-id>	</item>
		<item>
		<title>Drop last row of pandas dataframe in python (3 ways)</title>
		<link>https://python-programs.com/drop-last-row-of-pandas-dataframe-in-python/</link>
		
		<dc:creator><![CDATA[Satyabrata Jena]]></dc:creator>
		<pubDate>Fri, 03 Nov 2023 02:44:07 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=7303</guid>

					<description><![CDATA[<p>Dropping last row of pandas dataframe  (3 ways) in python In this article, we will three different ways to drop/ delete of a pandas dataframe. Use iloc to drop last row of pandas dataframe Use drop() to remove last row of pandas dataframe Use head() function to drop last row of pandas dataframe Use iloc [&#8230;]</p>
<p>The post <a href="https://python-programs.com/drop-last-row-of-pandas-dataframe-in-python/">Drop last row of pandas dataframe in python (3 ways)</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Dropping last row of pandas dataframe  (3 ways) in python</h2>
<p>In this article, we will three different ways to drop/ delete of a pandas dataframe.</p>
<ul>
<li><a href="#Use_iloc_to_drop_last_row_of_pandas_dataframe">Use iloc to drop last row of pandas dataframe</a></li>
<li><a href="#Use_drop()_to_remove_last_row_of_pandas_dataframe">Use drop() to remove last row of pandas dataframe</a></li>
<li><a href="#Use_head()_function_to_drop_last_row_of_pandas_dataframe">Use head() function to drop last row of pandas dataframe</a></li>
</ul>
<h3><a id="Use_iloc_to_drop_last_row_of_pandas_dataframe"></a>Use iloc to drop last row of pandas dataframe :</h3>
<p><strong> </strong>Dataframe from Pandas provide an attribute <em>iloc </em>that selects a portion of dataframe. We can take the help of this attribute, as this attribute can select all rows except last one and then assigning these rows back to the original variable, as a result last row will be deleted.</p>
<pre>Syntax of dataframe.iloc[]:- df.iloc[row_start:row_end , col_start, col_end]</pre>
<p>where,</p>
<p>Arguments:</p>
<ul>
<li><strong>row_start:</strong> The row index from which selection is started. Default value is 0.</li>
<li><strong>row_end:</strong> The row index at which selection should be end i.e. select till row_end-1. Default value is till the last row of the dataframe.</li>
<li><strong>col_start:</strong> The column index from which selection is started. Default is 0.</li>
<li><strong>col_end:</strong> The column index at which selection should be end i.e. select till end-1. Default value is till the last column of the dataframe.</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
# List of Tuples
players = [('Messi',35, 'Barcelona',   175) ,
            ('James',25, 'Tonga' ,   187) ,
            ('Hardik', 30, 'Mumbai',   169) ,
            ('Harsh',32, 'Mumabi',   201)]
# Creation of DataFrame object
dataf = sc.DataFrame(  players,
                    columns=['Name', 'Age', 'Team', 'Height'],
                    index = ['a', 'b', 'c', 'd'])
print("Original dataframe is : ")
print(dataf)
# Select last row except last row i.e. drops it
dataf = dataf.iloc[:-1 , :]
print("Modified Dataframe is : ")
print(dataf)
</pre>
<pre>Output :
Original dataframe is :
Name  Age       Team  Height
a   Messi   35  Barcelona     175
b   James   25      Tonga     187
c  Hardik   30     Mumbai     169
d   Harsh   32     Mumabi     201
Modified Dataframe is :
Name  Age       Team  Height
a   Messi   35  Barcelona     175
b   James   25      Tonga     187
c  Hardik   30     Mumbai     169</pre>
<h3><a id="Use_drop()_to_remove_last_row_of_pandas_dataframe"></a>Use drop() to remove last row of pandas dataframe :</h3>
<p><code>drop()</code> function deleted a sequence of rows. Only we have to use <em>axis=0 </em>&amp; pass argument <code>inplace=True</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
# List of Tuples
players = [('Messi',35, 'Barcelona',   175) ,
            ('James',25, 'Tonga' ,   187) ,
            ('Hardik', 30, 'Mumbai',   169) ,
            ('Harsh',32, 'Mumabi',   201)]
# Creation of DataFrame object
dataf = sc.DataFrame(  players,
                    columns=['Name', 'Age', 'Team', 'Height'],
                    index = ['a', 'b', 'c', 'd'])
print("Original dataframe is : ")
print(dataf)
# Drop the last row
dataf.drop(index=dataf.index[-1], 
        axis=0, 
        inplace=True)
print("Modified Dataframe is: ")
print(dataf)
</pre>
<pre>Output :
Original dataframe is :
Name  Age       Team  Height
a   Messi   35  Barcelona     175
b   James   25      Tonga     187
c  Hardik   30     Mumbai     169
d   Harsh   32     Mumabi     201
Modified Dataframe is:
Name  Age       Team  Height
a   Messi   35  Barcelona     175
b   James   25      Tonga     187
c  Hardik   30     Mumbai     169</pre>
<h3><a id="Use_head()_function_to_drop_last_row_of_pandas_dataframe"></a>Use head() function to drop last row of pandas dataframe :</h3>
<p>dataframe in Python provide head(n) function which returns first &#8216;n&#8217; rows of dataframe. So to the delete last row of dataframe we have to only select first (n-1) rows using<span style="color: #222222; font-family: monospace;"><span style="background-color: #e9ebec;"> head()</span></span> function.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
# List of Tuples
players = [('Messi',35, 'Barcelona',   175) ,
            ('James',25, 'Tonga' ,   187) ,
            ('Hardik', 30, 'Mumbai',   169) ,
            ('Harsh',32, 'Mumabi',   201)]
# Creation of DataFrame object
dataf = sc.DataFrame(  players,
                    columns=['Name', 'Age', 'Team', 'Height'],
                    index = ['a', 'b', 'c', 'd'])
print("Original dataframe is : ")
print(dataf)
# To delete last row, print first n-1 rows
dataf = dataf.head(dataf.shape[0] -1)
print("Modified Dataframe is : ")
print(dataf)
</pre>
<pre>Output :
Original dataframe is :
Name  Age       Team  Height
a   Messi   35  Barcelona     175
b   James   25      Tonga     187
c  Hardik   30     Mumbai     169
d   Harsh   32     Mumabi     201
Modified Dataframe is :
Name  Age       Team  Height
a   Messi   35  Barcelona     175
b   James   25      Tonga     187
c  Hardik   30     Mumbai     169</pre>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/drop-last-row-of-pandas-dataframe-in-python/">Drop last row of pandas dataframe in python (3 ways)</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">7303</post-id>	</item>
		<item>
		<title>How to Find and Drop duplicate columns in a DataFrame &#124; Python Pandas</title>
		<link>https://python-programs.com/how-to-find-and-drop-duplicate-columns-in-a-dataframe-python-pandas/</link>
		
		<dc:creator><![CDATA[Satyabrata Jena]]></dc:creator>
		<pubDate>Fri, 03 Nov 2023 02:43:54 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=7296</guid>

					<description><![CDATA[<p>Find &#38; Drop duplicate columns in a DataFrame &#124; Python Pandas In this article we will learn to find duplicate columns in a Pandas dataframe and drop them. Pandas library contain direct APIs to find out the duplicate rows, but there is no direct APIs for duplicate columns. And hence, we have to build API [&#8230;]</p>
<p>The post <a href="https://python-programs.com/how-to-find-and-drop-duplicate-columns-in-a-dataframe-python-pandas/">How to Find and Drop duplicate columns in a DataFrame | Python Pandas</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Find &amp; Drop duplicate columns in a DataFrame | Python Pandas</h2>
<p>In this article we will learn to find duplicate columns in a Pandas dataframe and drop them.</p>
<p>Pandas library contain direct APIs to find out the duplicate rows, but there is no direct APIs for duplicate columns. And hence, we have to build API for that. Initially let&#8217;s create a dataframe with duplicate columns.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
# List of Tuples
players = [('Nathan', 35, 'Australia', 35, 'Australia', 35),
            ('Vishal', 24, 'India', 24, 'India', 24),
            ('Abraham', 34, 'South Africa', 34, 'South Africa', 34),
            ('Trevor', 28, 'England', 28, 'England', 28),
            ('Kumar', 42, 'SriLanka', 42, 'SriLanka', 42),
            ]
# Create a DataFrame object
PlayerObj = sc.DataFrame(players, columns=['Name', 'Age', 'Country', 'Address', 'Citizen', 'Jersey'])
print("Original Dataframe is:")
print(PlayerObj)
</pre>
<pre>Output :
Original Dataframe is:
      Name  Age       Country  Address       Citizen  Jersey
0   Nathan   35     Australia       35     Australia      35
1   Vishal   24         India       24         India      24
2  Abraham   34  South Africa       34  South Africa      34
3   Trevor   28       England       28       England      28
4    Kumar   42      SriLanka       42      SriLanka      42
Original Dataframe is:
      Name  Age       Country  Address       Citizen  Jersey
0   Nathan   35     Australia       35     Australia      35
1   Vishal   24         India       24         India      24
2  Abraham  34  South Africa       34  South Africa      34
3   Trevor   28       England       28       England      28
4    Kumar   42      SriLanka       42      SriLanka      42</pre>
<h3>Find duplicate columns in a DataFrame :</h3>
<p>To find the duplicate columns in dataframe, we will iterate over each column and search if any other columns exist of same content. If yes, that column name will be stored in duplicate column list and in the end our API will returned list of duplicate columns.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
def getDuplicateColumns(df):
    '''
    Get a list of duplicate columns.
    It will iterate over all the columns and finfd the duplicate columns in dataframe
    :param df: Dataframe object
    :return: Column’s list whose contents are same
    '''
    duplicateColumnNames = set()
    # Iterate over all the columns 
    for x in range(df.shape[1]):
        # Select column at xth index of dataframe.
        col = df.iloc[:, x]
        # Iterate over all the columns from (x+1)th index till end
        for y in range(x + 1, df.shape[1]):
            # Select column at yth index of dataframe.
            otherCol = df.iloc[:, y]
            # Check if two columns x &amp; y are equal
            if col.equals(otherCol):
                duplicateColumnNames.add(df.columns.values[y])
    return list(duplicateColumnNames)
    
def main():
# List of Tuples
    players = [('Nathan', 35, 'Australia', 35, 'Australia', 35),
            ('Vishal', 24, 'India', 24, 'India', 24),
            ('Abraham', 34, 'South Africa', 34, 'South Africa', 34),
            ('Trevor', 28, 'England', 28, 'England', 28),
            ('Kumar', 42, 'SriLanka', 42, 'SriLanka', 42),
            ]
# Creation of DataFrame object
    PlayerObj = sc.DataFrame(players, columns=['Name', 'Age', 'Country', 'Address', 'Citizen', 'Jersey'])
    print("Original Dataframe is:")
    print(PlayerObj)
# To get list of duplicate columns
    duplicateColumnNames = getDuplicateColumns(PlayerObj)
    print('Duplicate Columns are: ')
    for ele in duplicateColumnNames:
        print('Column name is : ', ele)

if __name__ == '__main__':
    main()
</pre>
<pre>Output :
Original Dataframe is:
      Name  Age       Country  Address       Citizen  Jersey
0   Nathan   35     Australia       35     Australia      35
1   Vishal   24         India       24         India      24
2  Abraham   34  South Africa       34  South Africa      34
3   Trevor   28       England       28       England      28
4    Kumar   42      SriLanka       42      SriLanka      42
Duplicate Columns are:
('Column name is : ', 'Citizen')
('Column name is : ', 'Jersey')
('Column name is : ', 'Address')</pre>
<h3>Drop duplicate columns in a DataFrame :</h3>
<p>To drop/ remove the duplicate columns we will pass the list of duplicate column&#8217;s name which is returned by our API to <em>dataframe.drop.</em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
def getDuplicateColumns(df):
    '''
    Get a list of duplicate columns.
    It will iterate over all the columns and finfd the duplicate columns in dataframe
    :param df: Dataframe object
    :return: Column’s list whose contents are same
    '''
    duplicateColumnNames = set()
    # Iterate over all the columns 
    for x in range(df.shape[1]):
        # Select column at xth index of dataframe.
        col = df.iloc[:, x]
        # Iterate over all the columns from (x+1)th index till end
        for y in range(x + 1, df.shape[1]):
            # Select column at yth index of dataframe.
            otherCol = df.iloc[:, y]
            # Check if two columns x &amp; y are equal
            if col.equals(otherCol):
                duplicateColumnNames.add(df.columns.values[y])
    return list(duplicateColumnNames)
    
def main():
# List of Tuples
    players = [('Nathan', 35, 'Australia', 35, 'Australia', 35),
            ('Vishal', 24, 'India', 24, 'India', 24),
            ('Abraham', 34, 'South Africa', 34, 'South Africa', 34),
            ('Trevor', 28, 'England', 28, 'England', 28),
            ('Kumar', 42, 'SriLanka', 42, 'SriLanka', 42),
            ]
# Creation of DataFrame object
    PlayerObj = sc.DataFrame(players, columns=['Name', 'Age', 'Country', 'Address', 'Citizen', 'Jersey'])
    print("Original Dataframe is:")
    print(PlayerObj)
# To get list of duplicate columns
    duplicateColumnNames = getDuplicateColumns(PlayerObj)
    print('Duplicate Columns are: ')
    for ele in duplicateColumnNames:
        print('Column name is : ', ele)
    
 # Delete duplicate columns
    print('After removing duplicate columns new data frame becomes: ')
    newDf = PlayerObj.drop(columns=getDuplicateColumns(PlayerObj))
    print("Modified Dataframe is: ", newDf)

if __name__ == '__main__':
    main()
</pre>
<pre>Output :
Original Dataframe is:
Name  Age       Country  Address       Citizen  Jersey
0   Nathan   35     Australia       35     Australia      35
1   Vishal   24         India       24         India      24
2  Abraham   34  South Africa       34  South Africa      34
3   Trevor   28       England       28       England      28
4    Kumar   42      SriLanka       42      SriLanka      42
Duplicate Columns are:
Column name is :  Jersey
Column name is :  Citizen
Column name is :  Address
After removing duplicate columns new data frame becomes:
Modified Dataframe is:        Name  Age       Country
0   Nathan   35     Australia
1   Vishal   24         India
2  Abraham   34  South Africa
3   Trevor   28       England
4    Kumar   42      SriLanka</pre>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/how-to-find-and-drop-duplicate-columns-in-a-dataframe-python-pandas/">How to Find and Drop duplicate columns in a DataFrame | Python Pandas</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">7296</post-id>	</item>
		<item>
		<title>How to convert Dataframe column type from string to date time</title>
		<link>https://python-programs.com/how-to-convert-dataframe-column-type-from-string-to-date-time/</link>
		
		<dc:creator><![CDATA[Satyabrata Jena]]></dc:creator>
		<pubDate>Fri, 03 Nov 2023 02:43:17 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=7289</guid>

					<description><![CDATA[<p>Converting Dataframe column type from string to date time In this article we will learn to convert data type of dataframe column to from string to datetime where the data can be custom string formats or embedded in big texts. We will also learn how we can handle the error while converting data types. A [&#8230;]</p>
<p>The post <a href="https://python-programs.com/how-to-convert-dataframe-column-type-from-string-to-date-time/">How to convert Dataframe column type from string to date time</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Converting Dataframe column type from string to date time</h2>
<p>In this article we will learn to convert data type of dataframe column to from string to datetime where the data can be custom string formats or embedded in big texts. We will also learn how we can handle the error while converting data types.</p>
<p>A function provided by Python&#8217;s Pandas module is used to convert a given argument to datetime.</p>
<pre>Synatx : pandas.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin='unix', cache=True)</pre>
<p>where,</p>
<p><strong>Parameters:</strong></p>
<ul>
<li><strong>arg</strong> : Element that is to be converted to a datetime with type like int, float, string, datetime, list, 1-d array or Series.</li>
<li><strong>errors</strong> : It is a way to handle error which can be ‘ignore’, ‘raise’, ‘coerce’. Whereas, default value is ‘raise’ (‘<strong>raise</strong>’: Raise exception in invalid parsing , ‘<strong>coerce</strong>’: Set as NaT in case of invalid parsing , ‘<strong>ignore</strong>’: Return the input if invalid parsing found)</li>
<li><strong>format</strong> : string, default Nonedate &amp; time string in format eg “%d/%m/%Y” etc.</li>
</ul>
<p><strong> Returns:</strong></p>
<ul>
<li>It converts and return the value as date time format based on input.</li>
</ul>
<ol>
<li>A series of datetime64 type will be returned, if a series of string is passed.</li>
<li>A datetime64 object will be returned, if scalar entity is passed</li>
</ol>
<h3>Convert the Data type of a column from string to datetime64 :</h3>
<p>Let&#8217;s create a dataframe where column &#8216;DOB&#8217; has dates in string format i.e. DD/MM/YYYY’.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
# List of Tuples
players = [('Jason', '31/01/1978', 'Delhi', 155) ,
            ('Johny', '26/05/1980', 'Hyderabad' , 15) ,
            ('Darren', '03/01/1992', 'Jamaica',222) ,
            ('Finch', '22/12/1994','Pune' , 12) ,
            ('Krunal', '16/08/1979', 'Mumbai' , 58) ,
            ('Ravindra', '04/06/1985', 'Chennai', 99 ),
            ('Dinesh', '23/02/1985', 'Kolkata', 10)
           ]
# Creation of DataFrame object
PlayerObj = sc.DataFrame(players, columns=['Name', 'DOB', 'Teams', 'Jersey'])
print(PlayerObj)
print('Datatype of players dataframe is:')
print(PlayerObj.dtypes)
</pre>
<pre>Output :
       Name         DOB      Teams  Jersey
0     Jason  31/01/1978      Delhi     155
1     Johny  26/05/1980  Hyderabad      15
2    Darren  03/01/1992    Jamaica     222
3     Finch  22/12/1994       Pune      12
4    Krunal  16/08/1979     Mumbai      58
5  Ravindra  04/06/1985    Chennai      99
6    Dinesh  23/02/1985    Kolkata      10
Datatype of players dataframe is:
Name      object
DOB       object
Teams     object
Jersey     int64
dtype: object</pre>
<p>Now let&#8217;s try to convert data type of column &#8216;DOB&#8217; to datetime64.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
# List of Tuples
players = [('Jason', '31/01/1978', 'Delhi', 155) ,
            ('Johny', '26/05/1980', 'Hyderabad' , 15) ,
            ('Darren', '03/01/1992', 'Jamaica',222) ,
            ('Finch', '22/12/1994','Pune' , 12) ,
            ('Krunal', '16/08/1979', 'Mumbai' , 58) ,
            ('Ravindra', '04/06/1985', 'Chennai', 99 ),
            ('Dinesh', '23/02/1985', 'Kolkata', 10)
           ]
# Creation of DataFrame object
PlayerObj = sc.DataFrame(players, columns=['Name', 'DOB', 'Teams', 'Jersey'])
print(PlayerObj)
print('Datatype of players dataframe is:')
# Convert the column 'DOB' to datetime64 data type
PlayerObj['DOB'] = sc.to_datetime(PlayerObj['DOB'])
print(PlayerObj.dtypes)
</pre>
<p>Output :</p>
<pre>Name         DOB      Teams  Jersey
0     Jason  31/01/1978      Delhi     155
1     Johny  26/05/1980  Hyderabad      15
2    Darren  03/01/1992    Jamaica     222
3     Finch  22/12/1994       Pune      12
4    Krunal  16/08/1979     Mumbai      58
5  Ravindra  04/06/1985    Chennai      99
6    Dinesh  23/02/1985    Kolkata      10
Datatype of players dataframe is:
Name              object
DOB       datetime64[ns]
Teams             object
Jersey             int64
dtype: object</pre>
<p><code>to_datetime()</code> also converts the DOB strings in ISO8601 format to datetime64 type which automatically handles string types like. Henceforth, let&#8217;s try to convert data type of string to datetime64:</p>
<p>DD-MM-YYYY HH:MM AM/PM’</p>
<p>‘YYYY-MM-DDTHH:MM:SS’</p>
<p>‘YYYY-MM-DDT HH:MM:SS.ssssss’, etc.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
# List of Tuples
players = [('Jason', '31/01/1978 12:00 AM', 'Delhi', 155) ,
            ('Johny', '26/05/1980 02:00:55', 'Hyderabad' , 15) ,
            ('Darren', '03/01/1992', 'Jamaica',222) ,
            ('Finch', '22/12/1994 T23:11:25Z','Pune' , 12)
           ]
# Creation of DataFrame object
PlayerObj = sc.DataFrame(players, columns=['Name', 'DOB', 'Teams', 'Jersey'])
print(PlayerObj)
print('Datatype of players dataframe is:')
# Convert the column 'DOB' to datetime64 datatype
PlayerObj['DOB'] = sc.to_datetime(PlayerObj['DOB'])
print(PlayerObj.dtypes)
</pre>
<pre>Output :
Name                    DOB      Teams  Jersey
0   Jason    31/01/1978 12:00 AM      Delhi     155
1   Johny    26/05/1980 02:00:55  Hyderabad      15
2  Darren             03/01/1992    Jamaica     222
3   Finch  22/12/1994 T23:11:25Z       Pune      12
Datatype of players dataframe is:
Name              object
DOB       datetime64[ns]
Teams             object
Jersey             int64
dtype: object</pre>
<h3>Convert the Data type of a column from custom format string to datetime64 :</h3>
<p>We can also have case where the dataframe have columns having dates in custom format like DDMMYYYY, DD–MM–YY and then try to convert string format of custom format to datetime64.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
# List of Tuples
players = [('Jason', '08091986', 'Delhi', 155),
            ('Johny', '11101988', 'Hyderabad', 15)
            ]
# Creation of DataFrame object
PlayerObj = sc.DataFrame(players, columns=['Name', 'DOB', 'Teams', 'Jersey'])
print(PlayerObj)
print('Datatype of players dataframe is:')
# Convert the column 'DOB' to datetime64 datatype
PlayerObj['DOB'] = sc.to_datetime(PlayerObj['DOB'], format='%m%d%Y')
print(PlayerObj.dtypes)
</pre>
<pre>Output :
Name       DOB      Teams  Jersey
0  Jason  08091986      Delhi     155
1  Johny  11101988  Hyderabad      15
Datatype of players dataframe is:
Name              object
DOB       datetime64[ns]
Teams             object
Jersey             int64
dtype: object</pre>
<h3>Convert the Data type of a column from string to datetime by extracting date &amp; time strings from big string :</h3>
<p><strong> </strong>There may be a case where columns may contain: date of birth is 28101982 OR 17071990 is DOB. We have to pass the argument in <code>pd.to_dataframe()</code>, if passed as <em>False </em>it will try to match the format  anywhere in string. After that let&#8217;s convert data type of column DOB as string to datatime64.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
# List of Tuples
players = [('Jason', 'date of birth is 08091986', 'Delhi', 155),
            ('Johny', '11101988 is DOB', 'Hyderabad', 15)
            ]
# Creation of DataFrame object
PlayerObj = sc.DataFrame(players, columns=['Name', 'DOB', 'Teams', 'Jersey'])
print('Datatype of players dataframe is:')
# Convert the column 'DOB' to datetime64 data type
PlayerObj['DOB'] = sc.to_datetime(PlayerObj['DOB'], format='%m%d%Y', exact=False)
print(PlayerObj)
print(PlayerObj.dtypes)
</pre>
<pre>Output :
Datatype of players dataframe is:
    Name        DOB      Teams  Jersey
0  Jason 1986-08-09      Delhi     155
1  Johny 1988-11-10  Hyderabad      15
Name              object
DOB       datetime64[ns]
Teams             object
Jersey             int64
dtype: object</pre>
<h3>Another Example : Extract date &amp; time from big string in a column and add new columns of datetime64 format :</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc

# List of Tuples

players = [('Jason', '12:00 AM on the date 08091986', 'Delhi', 155),

            ('Johny', '11101988 and evening 07:00 PM', 'Hyderabad', 15)

            ]

# Creation of DataFrame object

PlayerObj = sc.DataFrame(players, columns=['Name', 'DOB', 'Teams', 'Jersey'])

print('Datatype of players dataframe is:')

# Convert the column 'DOB' to datetime64 data type

PlayerObj['DOB_time'] = sc.to_datetime(PlayerObj['DOB'], format='%H:%M %p', exact=False)

PlayerObj['DOB_date'] = sc.to_datetime(PlayerObj['DOB'], format='%m%d%Y', exact=False)

print('New dataframe is:')

print(PlayerObj)</pre>
<pre>Output :
Datatype of players dataframe is:
New dataframe is:
Name DOB ... DOB_time DOB_date
0 Jason 12:00 AM on the date 08091986 ... 1900-01-01 12:00:00 1986-08-09
1 Johny 11101988 and evening 07:00 PM ... 1900-01-01 07:00:00 1988-11-10</pre>
<p>In DOB_time column as we provided time only so it took date as default i.e. 1900-01-01, whereas DOB_date contains the date onle. But both the columns i.e. DOB_time &amp; DOB_date have same data type i.e. <em>datetime64.</em></p>
<h3>Handle error while Converting the Data type of a column from string to datetime :</h3>
<p>To handle the errors while converting data type of column we can pass error arguments like &#8216;raise&#8217;, &#8216;coerce&#8217;, &#8216;ignore&#8217; to customize the behavior.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as sc
# List of Tuples
players = [('Jason', '08091986', 'Delhi', 155),
            ('Johny', '11101988', 'Hyderabad', 15)
            ]

# Creation of DataFrame object
PlayerObj = sc.DataFrame(players, columns=['Name', 'DOB', 'Team', 'Jersey'])
print("Contents of the original Dataframe : ")
print(PlayerObj)
print('Data types of columns in original dataframe')
print(PlayerObj.dtypes)
# Ignores errors while converting the type
PlayerObj['DOB'] = sc.to_datetime(PlayerObj['DOB'], errors='ignore')
print("Contents of the Dataframe : ")
print(PlayerObj)
print('Data types of columns in modified dataframe')
print(PlayerObj.dtypes)
</pre>
<pre>Output :
Contents of the original Dataframe : 
Name DOB Team Jersey
0 Jason 08091986 Delhi 155
1 Johny 11101988 Hyderabad 15
Data types of columns in original dataframe
Name object
DOB object
Team object
Jersey int64
dtype: object
Contents of the Dataframe : 
Name DOB Team Jersey
0 Jason 08091986 Delhi 155
1 Johny 11101988 Hyderabad 15
Data types of columns in modified dataframe
Name object
DOB object
Team object
Jersey int64
dtype: object</pre>
<p>Want to expert in the python programming language? Exploring <a href="https://python-programs.com/python-data-analysis-using-pandas/">Python Data Analysis using Pandas</a> tutorial changes your knowledge from basic to advance level in python concepts.</p>
<p><strong>Read more Articles on Python Data Analysis Using Padas – Modify a Dataframe</strong></p>
<ul>
<li><a href="https://python-programs.com/pandas-apply-apply-a-function-to-each-row-column-in-dataframe/">pandas.apply(): Apply a function to each row/column in Dataframe</a></li>
<li><a href="https://python-programs.com/pandas-sort-rows-or-columns-in-dataframe-based-on-values-using-dataframe-sort_values/">Pandas: Sort rows or columns in Dataframe based on values using Dataframe.sort_values()</a></li>
<li><a href="https://python-programs.com/pandas-apply-a-function-to-single-or-selected-columns-or-rows-in-dataframe/">Apply a function to single or selected columns or rows in Dataframe</a></li>
<li><a href="https://python-programs.com/pandas-sort-a-dataframe-based-on-column-names-or-row-index-labels-using-dataframe-sort_index/">Sort a DataFrame based on column names or row index labels using Dataframe.sort_index() in Pandas</a></li>
<li><a href="https://python-programs.com/pandas-change-data-type-of-single-or-multiple-columns-of-dataframe-in-python/">Change data type of single or multiple columns of Dataframe in Python</a></li>
<li><a href="https://python-programs.com/python-pandas-replace-or-change-column-row-index-names-in-dataframe/">Change Column &amp; Row names in DataFrame</a></li>
<li><a href="https://python-programs.com/convert-pandas-dataframe-column-into-an-index-using-set_index-in-python/">Convert Dataframe column into to the Index of Dataframe</a></li>
<li><a href="https://python-programs.com/pandas-convert-data-frame-index-into-column-using-dataframe-reset_index-in-python/">Convert Dataframe indexes into columns</a></li>
</ul>
<p>The post <a href="https://python-programs.com/how-to-convert-dataframe-column-type-from-string-to-date-time/">How to convert Dataframe column type from string to date time</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">7289</post-id>	</item>
		<item>
		<title>What is a Structured Numpy Array and how to create and sort it in Python?</title>
		<link>https://python-programs.com/what-is-a-structured-numpy-array-and-how-to-create-and-sort-it-in-python/</link>
		
		<dc:creator><![CDATA[Satyabrata Jena]]></dc:creator>
		<pubDate>Fri, 03 Nov 2023 02:42:58 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=7279</guid>

					<description><![CDATA[<p>Structured Numpy Array and how to create and sort it in Python In this article we will learn what is structured numpy array, how to create it and how to sort with different functions. Creating a Structured Numpy Array How to Sort a Structured Numpy Array ? What is a Structured Numpy Array ? A [&#8230;]</p>
<p>The post <a href="https://python-programs.com/what-is-a-structured-numpy-array-and-how-to-create-and-sort-it-in-python/">What is a Structured Numpy Array and how to create and sort it in Python?</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Structured Numpy Array and how to create and sort it in Python</h2>
<p>In this article we will learn what is structured numpy array, how to create it and how to sort with different functions.</p>
<ul>
<li><a href="#Creating_a_Structured_Numpy_Array">Creating a Structured Numpy Array</a></li>
<li><a href="#How_to_Sort_a_Structured_Numpy_Array_?">How to Sort a Structured Numpy Array ?</a></li>
</ul>
<h3>What is a Structured Numpy Array ?</h3>
<p>A Structured Numpy array is an array of structures where we can also make of homogeneous structures too.</p>
<h3><a id="Creating_a_Structured_Numpy_Array"></a>Creating a Structured Numpy Array</h3>
<p>To create structured numpy array we will pass list of tuples with elements in dtype parameter and we will create numpy array based on this stype.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as sc

# Creation of structure

dtype = [('Name', (sc.str_, 10)), ('CGPA', sc.float64), ('Age', sc.int32)]

# Creation a Strucured Numpy array

structured_arr = sc.array([('Ben',8.8 , 18), ('Rani', 9.4, 15), ('Tanmay', 9.8, 17), ('Saswat', 7.6, 16)], dtype=dtype)

print(structured_arr.dtype)</pre>
<pre>Output :
[('Name', '&lt;U10'), ('CGPA', '&lt;f8'), ('Age', '&lt;i4')]</pre>
<h3>Sort the Structured Numpy array by field ‘Name&#8217; of the structure</h3>
<h3><a id="How_to_Sort_a_Structured_Numpy_Array_?"></a>How to Sort a Structured Numpy Array ?</h3>
<p>We can sort a big structured numpy array by providing a parameter <em>&#8216;order&#8217;</em> parameter provided by <code>numpy.sort()</code> and <code>numpy.ndarray.sort()</code>. Let&#8217;s sort the structured numpy array on the basis of field &#8216;<code>Name</code>&#8216;.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as sc

# Creation of structure

dtype = [('Name', (sc.str_, 10)), ('CGPA', sc.float64), ('Age', sc.int32)]

# Creation a Strucured Numpy array

structured_arr = sc.array([('Ben',8.8 , 18), ('Rani', 9.4, 15), ('Tanmay', 9.8, 17), ('Saswat', 7.6, 16)], dtype=dtype)

sor_arr = sc.sort(structured_arr, order='Name')

print('Sorted Array on the basis on name : ')

print(sor_arr)</pre>
<pre>Output :
Sorted Array on the basis on name :
[('Ben', 8.8, 18) ('Rani', 9.4, 15) ('Saswat', 7.6, 16)
('Tanmay', 9.8, 17)]</pre>
<h3>Sort the Structured Numpy array by field ‘Age&#8217; of the structure</h3>
<p>We can also sort the structured numpy array on the basis of field &#8216;<code>Marks</code>&#8216;.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as sc

# Creation of structure

dtype = [('Name', (sc.str_, 10)), ('CGPA', sc.float64), ('Age', sc.int32)]

# Creation a Strucured Numpy array

structured_arr = sc.array([('Ben',8.8 , 18), ('Rani', 9.4, 15), ('Tanmay', 9.8, 17), ('Saswat', 7.6, 16)], dtype=dtype)

sor_arr = sc.sort(structured_arr, order='Age')

print('Sorted Array on the basis on Age : ')

print(sor_arr)</pre>
<pre>Output :
Sorted Array on the basis on Age :
[('Rani', 9.4, 15) ('Saswat', 7.6, 16) ('Tanmay', 9.8, 17)
('Ben', 8.8, 18)]</pre>
<h3>Sort the Structured Numpy array by ‘Name’ &amp; ‘Age’ fields of the structure :</h3>
<p>We can also sort Structured Numpy array based on multiple fields &#8216;<code>Name</code>&#8216; &amp; &#8216;<code>Age</code>&#8216;.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as sc

# Creation of structure

dtype = [('Name', (sc.str_, 10)), ('CGPA', sc.float64), ('Age', sc.int32)]

# Creation a Strucured Numpy array

structured_arr = sc.array([('Ben',8.8 , 18), ('Rani', 9.4, 15), ('Tanmay', 9.8, 17), ('Saswat', 7.6, 16)], dtype=dtype)

sor_arr = sc.sort(structured_arr, order=['Name','Age'])

print('Sorted Array on the basis on name &amp; age : ')

print(sor_arr)</pre>
<pre>Output :
Sorted Array on the basis on name &amp; age:
[('Ben', 8.8, 18) ('Rani', 9.4, 15) ('Saswat', 7.6, 16)
('Tanmay', 9.8, 17)]</pre>
<p>The post <a href="https://python-programs.com/what-is-a-structured-numpy-array-and-how-to-create-and-sort-it-in-python/">What is a Structured Numpy Array and how to create and sort it in Python?</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">7279</post-id>	</item>
		<item>
		<title>Python : How to get the list of all files in a zip archive</title>
		<link>https://python-programs.com/python-how-to-get-the-list-of-all-files-in-a-zip-archive/</link>
		
		<dc:creator><![CDATA[Satyabrata Jena]]></dc:creator>
		<pubDate>Thu, 02 Nov 2023 15:08:27 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=7776</guid>

					<description><![CDATA[<p>How to get the list of all files in a zip archive in Python In this article we will learn about various ways to get detail about all files in a zip archive like file’s name, size etc. How to find name of all the files in the ZIP archive using ZipFile.namelist() : ZipFile class [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-how-to-get-the-list-of-all-files-in-a-zip-archive/">Python : How to get the list of all files in a zip archive</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>How to get the list of all files in a zip archive in Python</h2>
<p>In this article we will learn about various ways to get detail about all files in a zip archive like file’s name, size etc.</p>
<h3>How to find name of all the files in the ZIP archive using ZipFile.namelist() :</h3>
<p><span style="color: #222222;font-family: monospace"><span style="background-color: #e9ebec">ZipFile</span></span> class from <code>zipfile</code> module provide a member function i.e. <code>ZipFile.namelist()</code> to get the names of all files present it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">from zipfile import ZipFile
def main():
    # To Create a ZipFile Object and load Document.zip in it
    with ZipFile('DocumentDir.zip', 'r') as zip_Obj:
       # To get list of files names in zip
       fileslist = zip_Obj.namelist()
       # Iterate over the fileslist names in given list &amp; print them
       for ele in fileslist:
           print(ele)
if __name__ == '__main__':
    main()
</pre>
<pre>Output :
DocumentDir/doc1.csv
DocumentDir/doc2.csv
DocumentDir/test.csv</pre>
<h3>Find detail info like name, size etc of the files in a Zip file using ZipFile.infolist() :</h3>
<p><code><code>ZipFile</code></code> class from <code>zipfile</code> module also provide a member function i.e. <code>ZipFile.infolist()</code> to get the details of each entries present in zipfile.</p>
<p>Here a list of <em>ZipInfo </em>objects is returned where each object has certain information like name, permission, size etc.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">from zipfile import ZipFile
def main():
        # To Create a ZipFile Object and load Document.zip in it
    with ZipFile('DocumentDir.zip', 'r') as zip_Obj:
        # Get list of ZipInfo objects
        fileslist = zip_Obj.infolist()
        # Iterate of over object’s list and also to access members of the object
        for ele in fileslist:
            print(ele.filename, ' : ', ele.file_size, ' : ', ele.date_time, ' : ', ele.compress_size)
if __name__ == '__main__':
    main()
</pre>
<pre>Output :
DocumentDir/doc1.csv :  2759  :  (2021, 01, 03, 21, 00, 02)  :  2759
DocumentDir/doc2.csv :  2856  :  (2021, 01, 25, 13, 45, 58)  :  2856
DocumentDir/test.csv  :  3458  :  (2021, 02, 20, 20, 20, 41)  :  3458</pre>
<h3>Details of ZIP archive to std.out using ZipFile.printdir() :</h3>
<p><code><code>ZipFile</code></code> class from <code>zipfile</code> module also provide a member function i.e. <code>ZipFile.printdir()</code> which can print the contents of zip file as table.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">from zipfile import ZipFile
def main():
    # To Create a ZipFile Object and load Document.zip in it
    with ZipFile('DocumentDir.zip', 'r') as zip_Obj:
        zip_Obj.printdir()
if __name__ == '__main__':
    main()
</pre>
<pre>Output :
File Name                                             Modified                         Size
DocumentDir/doc1.csv                      2021-01-03 21:00:02         2759
DocumentDir/doc2.csv                      2021-01-25 13:45:58         2856
DocumentDir/test.csv                        2021-02-20 20:20:41         3458</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/python-how-to-get-the-list-of-all-files-in-a-zip-archive/">Python : How to get the list of all files in a zip archive</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">7776</post-id>	</item>
		<item>
		<title>Create a Thread using Class in Python</title>
		<link>https://python-programs.com/create-a-thread-using-class-in-python/</link>
		
		<dc:creator><![CDATA[Satyabrata Jena]]></dc:creator>
		<pubDate>Wed, 01 Nov 2023 09:57:12 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=7054</guid>

					<description><![CDATA[<p>Creating a Thread using Class in Python In this article, we will discuss how we can create thread in python by extending class from Thread class or calling a member function of the class. Python provides a threading module to create and manage threads. Extend Thread class to create Threads : Let&#8217;s create a FileLoadTh [&#8230;]</p>
<p>The post <a href="https://python-programs.com/create-a-thread-using-class-in-python/">Create a Thread using Class in Python</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Creating a Thread using Class in Python</h2>
<p>In this article, we will discuss how we can create thread in python by extending class from Thread class or calling a member function of the class.</p>
<p>Python provides a threading module to create and manage threads.</p>
<h3>Extend Thread class to create Threads :</h3>
<p>Let&#8217;s create a <code>FileLoadTh</code> class by extending Thread class provided by the threading module where it mimics functionality of a File loader and it&#8217;s <code>run()</code> method sleeps for sometime.</p>
<p>When we start thread by calling <code>start()</code> function, it will invoke run() method of Thread class and overriden <code>run()</code> method will be executed which may contain any custom implementation.</p>
<p>It is better to wait for other threads to finish calling <code>join()</code> method on <code>FileLoaderTh</code> class object before returning from main thread.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">from threading import Thread
import time
# FileLoadTh extending Thread class
class FileLoaderTh(Thread):
   def __init__(self, fileName, encryptionType):
       # Calling Thread class's init() function
       Thread.__init__(self)
       self.fileName = fileName
       self.encryptionType = encryptionType
   # Overriding run() of Thread class
   def run(self):
       print('Loading started from file : ', self.fileName)
       print('Encryption Type : ', self.encryptionType)
       for i in range(5):
           print('Please wait loading... ')
           time.sleep(3)
       print('Loading finished from file : ', self.fileName)
def main():
   # Create an object of Thread
   th = FileLoaderTh('threadDemo.csv','DOC')
   # calling Thread class start() to start the thread
   th.start()
   for i in range(5):
       print('Inside main function-------')
       time.sleep(3)
   # Wait for thread to finish
   th.join()
if __name__ == '__main__':
   main()
</pre>
<pre>Output :
Loading started from file :  threadDemo.csv
Inside main function-------
Encryption Type :  DOC
Please wait loading...
Inside main function-------
Please wait loading...
Inside main function-------
Please wait loading...
Please wait loading...
Inside main function-------
Please wait loading...
Inside main function-------
Loading finished from file :  threadDemo.csv</pre>
<h3>Create a Thread from a member function of a class :</h3>
<p>Now let&#8217;s create a thread that executes <code>loadcont()</code> memeber function of <code>FileLoadTh</code> class. For that we can create a object and then pass the function with object to target argument of Thread class constructor.</p>
<p>So both <code>main()</code> function and <code>loadcont()</code> member function will run in parallel and at the end main() function will wait for other threads calling <code>join()</code> function on the same object.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import threading
import time
class FileLoaderTh():
   def __init__(self):
       pass
   
   def loadcont(self, fileName, encryptionType):
       print('Loading started from file : ', fileName)
       print('Encryption Type : ', encryptionType)
       for i in range(5):
           print('Loading ... ')
           time.sleep(3)
       print('Loading finished from file : ', fileName)
def main():
   # Creating object of FileLoaderTh class
   fileLoader = FileLoaderTh()
   # Create a thread using member function of FileHolderTh class
   th = threading.Thread(target=fileLoader.loadcont, args=('threadDemo.csv','DOC', ))
   # Start a thread
   th.start()
   # Print some logs in main thread
   for i in range(5):
       print('Inside main Function')
       time.sleep(3)
   # Wait for thread to finish
   th.join()
if __name__ == '__main__':
   main()
</pre>
<pre>Output :
Loading started from file :  threadDemo.csv
Encryption Type :  DOC
Inside main Function
Loading ...
Inside main Function
Loading ...
Inside main Function
Loading ...
Inside main Function
Loading ...
Loading ...
Inside main Function
Loading finished from file :  threadDemo.csv</pre>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/create-a-thread-using-class-in-python/">Create a Thread using Class in Python</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">7054</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: python-programs.com @ 2026-04-19 17:48:25 by W3 Total Cache
-->