<?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>Shikha Mishra, Author at Python Programs</title>
	<atom:link href="https://python-programs.com/author/shikha/feed/" rel="self" type="application/rss+xml" />
	<link>https://python-programs.com/author/shikha/</link>
	<description>Python Programs with Examples, How To Guides on Python</description>
	<lastBuildDate>Fri, 10 Nov 2023 06:42:11 +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>Python Word Count (Filter out Punctuation, Dictionary Manipulation, and Sorting Lists)</title>
		<link>https://python-programs.com/python-word-count-filter-out-punctuation-dictionary-manipulation-and-sorting-lists/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Wed, 01 Nov 2023 07:51:59 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=6982</guid>

					<description><![CDATA[<p>In this tutorial, we will discuss python word count (Filter out Punctuation, Dictionary Manipulation, and Sorting Lists). Also, you guys can see some of the approaches on Output a List of Word Count Pairs. Let&#8217;s use the below links and have a quick reference on this python concept. How to count the number of words [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-word-count-filter-out-punctuation-dictionary-manipulation-and-sorting-lists/">Python Word Count (Filter out Punctuation, Dictionary Manipulation, and Sorting Lists)</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this tutorial, we will discuss python word count (Filter out Punctuation, Dictionary Manipulation, and Sorting Lists). Also, you guys can see some of the approaches on Output a List of Word Count Pairs. Let&#8217;s use the below links and have a quick reference on this python concept.</p>
<ul>
<li><a href="#How_to_count_the_number_of_words_in_a_sentence,_ignoring_numbers,_punctuation,_and_whitespace?">How to count the number of words in a sentence, ignoring numbers, punctuation, and whitespace?</a></li>
<li><a href="#Output_a_List_of_Word_Count_Pairs_(Sorted_from_Highest_to_Lowest)">Output a List of Word Count Pairs (Sorted from Highest to Lowest)</a></li>
<li><a href="#Approach_1:_Collections_Module">Approach 1: Collections Module</a></li>
<li><a href="#Approach_2:_Using_For_Loops">Approach 2: Using For Loops</a></li>
<li><a href="#Approach_3:_Not_using_Dictionary_Get_Method">Approach 3: Not using Dictionary Get Method</a></li>
<li><a href="#Approach_4:_Using_sorted">Approach 4: Using sorted</a></li>
</ul>
<h2><a id="How_to_count_the_number_of_words_in_a_sentence,_ignoring_numbers,_punctuation,_and_whitespace?"></a>How to count the number of words in a sentence, ignoring numbers, punctuation, and whitespace?</h2>
<p>First, we will take a paragraph after that we will clean punctuation and transform all words to lowercase. Then we will count how many times each word occurs in that paragraph.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">Text="Python can be easy to pick up whether you're a first time programmer or you're experienced with other languages. The following pages are a useful first step to get on your way writing programs with Python!The community hosts conferences and meetups, collaborates on code, and much more. Python's documentation will help you along the way, and the mailing lists will keep you in touch.Python is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. Python's license is administered.Python is a general-purpose coding language—which means that, unlike HTML, CSS, and JavaScript, it can be used for other types of programming and software development besides web development. That includes back end development, software development, data science and writing system scripts among other things."
for char in '-.,\n':
Text=Text.replace(char,' ')
Text = Text.lower()
# split returns a list of words delimited by sequences of whitespace (including tabs, newlines, etc, like re's \s) 
word_list = Text.split()
print(word_list)</pre>
<p><strong>Output:</strong></p>
<pre>['python', 'can', 'be', 'easy', 'to', 'pick', 'up', 'whether', 
"you're", 'a', 'first', 'time', 'programmer', 'or', "you're",
 'experienced', 'with', 'other', 'languages', 'the', 'following', 
'pages', 'are', 'a', 'useful', 'first', 'step', 'to', 'get', 'on', 'your', 
'way', 'writing', 'programs', 'with', 'python!the', 'community',
 'hosts', 'conferences', 'and', 'meetups', 'collaborates', 'on', 'code', 
'and', 'much', 'more', "python's", 'documentation', 'will', 'help', 'you',
 'along', 'the', 'way', 'and', 'the', 'mailing', 'lists', 'will', 'keep', 'you', 'in',
 'touch', 'python', 'is', 'developed', 'under', 'an', 'osi', 'approved', 'open',
 'source', 'license', 'making', 'it', 'freely', 'usable', 'and', 'distributable', 
'even', 'for', 'commercial', 'use', "python's", 'license', 'is', 'administered', 
'python', 'is', 'a', 'general', 'purpose', 'coding', 'language—which', 'means', 
'that', 'unlike', 'html', 'css', 'and', 'javascript', 'it', 'can', 'be', 'used', 'for', 'other', 
'types', 'of', 'programming', 'and', 'software', 'development', 'besides', 'web', 
'development', 'that', 'includes', 'back', 'end', 'development', 'software', 
'development', 'data', 'science', 'and', 'writing', 'system', 'scripts', 'among', 'other', 'things']
</pre>
<p>So in the above output, you can see a list of word count pairs which is sorted from highest to lowest.</p>
<p>Thus, now we are going to discuss some approaches.</p>
<p><span style="color: #ff6600;">Also Check:</span></p>
<ul>
<li><a href="https://python-programs.com/python-ways-to-remove-duplicates-from-list/">Python – Ways to remove duplicates from list</a></li>
<li><a href="https://python-programs.com/convert-integer-to-string-in-python/">Convert integer to string in Python</a></li>
</ul>
<h2><a id="Output_a_List_of_Word_Count_Pairs_(Sorted_from_Highest_to_Lowest)"></a>Output a List of Word Count Pairs (Sorted from Highest to Lowest)</h2>
<h3><a id="Approach_1:_Collections_Module"></a>1. Collections Module:</h3>
<p>The collections module approach is the easiest one but for using this we have to know which library we are going to use.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">from collections import Counter

Counter(word_list).most_common()</pre>
<p>In this, collections module, we will import the counter then implement this in our programme.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">from collections import Counter
Text="Python can be easy to pick up whether you're a first time programmer or you're experienced with other languages. The following pages are a useful first step to get on your way writing programs with Python!The community hosts conferences and meetups, collaborates on code, and much more. Python's documentation will help you along the way, and the mailing lists will keep you in touch.Python is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. Python's license is administered.Python is a general-purpose coding language—which means that, unlike HTML, CSS, and JavaScript, it can be used for other types of programming and software development besides web development. That includes back end development, software development, data science and writing system scripts among other things."
word_list = Text.split()
count=Counter(word_list).most_common()
print(count)</pre>
<p><strong>Output:</strong></p>
<pre>[('and', 7), ('a', 3), ('other', 3), ('is', 3), ('can', 2), ('be', 2), ('to', 2), 
("you're", 2), ('first', 2), ('with', 2), ('on', 2), ('writing', 2), ("Python's", 2),
 ('will', 2), ('you', 2), ('the', 2), ('it', 2), ('for', 2), ('software', 2), ('development,', 2), 
('Python', 1), ('easy', 1), ('pick', 1), ('up', 1), ('whether', 1), ('time', 1), ('programmer', 1),
 ('or', 1), ('experienced', 1), ('languages.', 1), ('The', 1), ('following', 1), ('pages', 1), ('are', 1), 
('useful', 1), ('step', 1), ('get', 1), ('your', 1), ('way', 1), ('programs', 1), ('Python!The', 1), 
('community', 1), ('hosts', 1), ('conferences', 1), ('meetups,', 1), ('collaborates', 1), ('code,', 1), 
('much', 1), ('more.', 1), ('documentation', 1), ('help', 1), ('along', 1), ('way,', 1), ('mailing', 1),
 ('lists', 1), ('keep', 1), ('in', 1), ('touch.Python', 1), ('developed', 1), ('under', 1), ('an', 1),
 ('OSI-approved', 1), ('open', 1), ('source', 1), ('license,', 1), ('making', 1), ('freely', 1),
 ('usable', 1), ('distributable,', 1), ('even', 1), ('commercial', 1), ('use.', 1), ('license', 1), 
('administered.Python', 1), ('general-purpose', 1), ('coding', 1), ('language—which', 1), ('means', 1),
 ('that,', 1), ('unlike', 1), ('HTML,', 1), ('CSS,', 1), ('JavaScript,', 1), ('used', 1), ('types', 1), ('of', 1), 
('programming', 1), ('development', 1), ('besides', 1), ('web', 1), ('development.', 1), ('That', 1), 
('includes', 1), ('back', 1), ('end', 1), ('data', 1), ('science', 1), ('system', 1), ('scripts', 1), ('among', 1), ('things.', 1)]
</pre>
<h3><a id="Approach_2:_Using_For_Loops"></a>2. Using For Loops:</h3>
<p>This is the second approach and in this, we will use for loop and dictionary get method.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">from collections import Counter
Text="Python can be easy to pick up whether you're a first time programmer or you're experienced with other languages. The following pages are a useful first step to get on your way writing programs with Python!The community hosts conferences and meetups, collaborates on code, and much more. Python's documentation will help you along the way, and the mailing lists will keep you in touch.Python is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. Python's license is administered.Python is a general-purpose coding language—which means that, unlike HTML, CSS, and JavaScript, it can be used for other types of programming and software development besides web development. That includes back end development, software development, data science and writing system scripts among other things."
word_list = Text.split()
# Initializing Dictionary
d = {}
# counting number of times each word comes up in list of words (in dictionary)
for word in word_list: 
    d[word] = d.get(word, 0) + 1
word_freq = []
for key, value in d.items():
    word_freq.append((value, key))
word_freq.sort(reverse=True) 
print(word_freq)</pre>
<p><strong>Output:</strong></p>
<pre>[(7, 'and'), (3, 'other'), (3, 'is'), (3, 'a'), (2, "you're"), (2, 'you'), (2, 'writing'),
 (2, 'with'), (2, 'will'), (2, 'to'), (2, 'the'), (2, 'software'), (2, 'on'), (2, 'it'), (2, 'for'), (
2, 'first'), (2, 'development,'), (2, 'can'), (2, 'be'), (2, "Python's"), (1, 'your'), (1, 'whether'),
 (1, 'web'), (1, 'way,'), (1, 'way'), (1, 'useful'), (1, 'used'), (1, 'use.'), (1, 'usable'), (1, 'up'), 
(1, 'unlike'), (1, 'under'), (1, 'types'), (1, 'touch.Python'), (1, 'time'), (1, 'things.'), (1, 'that,'), 
(1, 'system'), (1, 'step'), (1, 'source'), (1, 'scripts'), (1, 'science'), (1, 'programs'),
 (1, 'programming'), (1, 'programmer'), (1, 'pick'), (1, 'pages'), (1, 'or'), (1, 'open'), 
(1, 'of'), (1, 'much'), (1, 'more.'), (1, 'meetups,'), (1, 'means'), (1, 'making'), (1, 'mailing'),
 (1, 'lists'), (1, 'license,'), (1, 'license'), (1, 'language—which'), (1, 'languages.'), (1, 'keep'),
 (1, 'includes'), (1, 'in'), (1, 'hosts'), (1, 'help'), (1, 'get'), (1, 'general-purpose'), (1, 'freely'), 
(1, 'following'), (1, 'experienced'), (1, 'even'), (1, 'end'), (1, 'easy'), (1, 'documentation'),
 (1, 'distributable,'), (1, 'development.'), (1, 'development'), (1, 'developed'), (1, 'data'), 
(1, 'conferences'), (1, 'community'), (1, 'commercial'), (1, 'collaborates'), (1, 'coding'), 
(1, 'code,'), (1, 'besides'), (1, 'back'), (1, 'are'), (1, 'an'), (1, 'among'), (1, 'along'), (1, 'administered.Python'),
 (1, 'The'), (1, 'That'), (1, 'Python!The'), (1, 'Python'), (1, 'OSI-approved'), (1, 'JavaScript,'), (1, 'HTML,'), (1, 'CSS,')]
</pre>
<p>So in the above approach, we have used for loop after that we reverse the key and values so they can be sorted using tuples. Now we sorted from lowest to highest.</p>
<h3><a id="Approach_3:_Not_using_Dictionary_Get_Method"></a>3. Not using Dictionary Get Method:</h3>
<p>So in this approach, we will not use the get method dictionary.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">from collections import Counter
Text="Python can be easy to pick up whether you're a first time programmer or you're experienced with other languages. The following pages are a useful first step to get on your way writing programs with Python!The community hosts conferences and meetups, collaborates on code, and much more. Python's documentation will help you along the way, and the mailing lists will keep you in touch.Python is developed under an OSI-approved open source license, making it freely usable and distributable, even for commercial use. Python's license is administered.Python is a general-purpose coding language—which means that, unlike HTML, CSS, and JavaScript, it can be used for other types of programming and software development besides web development. That includes back end development, software development, data science and writing system scripts among other things."
word_list = Text.split()
# Initializing Dictionary
d = {}

# Count number of times each word comes up in list of words (in dictionary)
for word in word_list:
    if word not in d:
        d[word] = 0
    d[word] += 1
word_freq = []
for key, value in d.items():
    word_freq.append((value, key))
word_freq.sort(reverse=True)
print(word_freq)</pre>
<p><strong>Output:</strong></p>
<pre>[(7, 'and'), (3, 'other'), (3, 'is'), (3, 'a'), (2, "you're"), (2, 'you'), (2, 'writing'),
 (2, 'with'), (2, 'will'), (2, 'to'), (2, 'the'), (2, 'software'), (2, 'on'), (2, 'it'), (2, 'for'), (2, 'first'), 
(2, 'development,'), (2, 'can'), (2, 'be'), (2, "Python's"), (1, 'your'), (1, 'whether'), (1, 'web'),
 (1, 'way,'), (1, 'way'), (1, 'useful'), (1, 'used'), (1, 'use.'), (1, 'usable'), (1, 'up'), (1, 'unlike'),
 (1, 'under'), (1, 'types'), (1, 'touch.Python'), (1, 'time'), (1, 'things.'), (1, 'that,'), (1, 'system'), 
(1, 'step'), (1, 'source'), (1, 'scripts'), (1, 'science'), (1, 'programs'), (1, 'programming'), 
(1, 'programmer'), (1, 'pick'), (1, 'pages'), (1, 'or'), (1, 'open'), (1, 'of'), (1, 'much'),
 (1, 'more.'), (1, 'meetups,'), (1, 'means'), (1, 'making'), (1, 'mailing'), (1, 'lists'), (1, 'license,'), 
(1, 'license'), (1, 'language—which'), (1, 'languages.'), (1, 'keep'), (1, 'includes'), (1, 'in'), (1, 'hosts'),
 (1, 'help'), (1, 'get'), (1, 'general-purpose'), (1, 'freely'), (1, 'following'), (1, 'experienced'), 
(1, 'even'), (1, 'end'), (1, 'easy'), (1, 'documentation'), (1, 'distributable,'), (1, 'development.'),
 (1, 'development'), (1, 'developed'), (1, 'data'), (1, 'conferences'), (1, 'community'), (1, 'commercial'),
 (1, 'collaborates'), (1, 'coding'), (1, 'code,'), (1, 'besides'), (1, 'back'), (1, 'are'), (1, 'an'), (1, 'among'),
 (1, 'along'), (1, 'administered.Python'), (1, 'The'), (1, 'That'), (1, 'Python!The'), (1, 'Python'), 
(1, 'OSI-approved'), (1, 'JavaScript,'), (1, 'HTML,'), (1, 'CSS,')]
</pre>
<h3><a id="Approach_4:_Using_sorted"></a>4. Using Sorted:</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># initializing a dictionary
d = {};

# counting number of times each word comes up in list of words
for key in word_list: 
    d[key] = d.get(key, 0) + 1

sorted(d.items(), key = lambda x: x[1], reverse = True)</pre>
<h3>Conclusion:</h3>
<p>In this article, you have seen different approaches on how to count the number of words in a sentence, ignoring numbers, punctuation, and whitespace. Thank you!</p>
<p>The post <a href="https://python-programs.com/python-word-count-filter-out-punctuation-dictionary-manipulation-and-sorting-lists/">Python Word Count (Filter out Punctuation, Dictionary Manipulation, and Sorting Lists)</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6982</post-id>	</item>
		<item>
		<title>Python: How to convert a timestamp string to a datetime object using datetime.strptime()</title>
		<link>https://python-programs.com/python-how-to-convert-a-timestamp-string-to-a-datetime-object-using-datetime-strptime/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Mon, 30 Oct 2023 11:01:35 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=6315</guid>

					<description><![CDATA[<p>In this tutorial, we will learn how to convert a timestamp string to a datetime object using datetime.strptime(). Also, you can understand how to to create a datetime object from a string in Python with examples below. String to a DateTime object using datetime.strptime() Format Code List How strptime() works? Examples of converting a Time [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-how-to-convert-a-timestamp-string-to-a-datetime-object-using-datetime-strptime/">Python: How to convert a timestamp string to a datetime object using datetime.strptime()</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this tutorial, we will learn how to convert a timestamp string to a datetime object using datetime.strptime(). Also, you can understand how to to create a datetime object from a string in Python with examples below.</p>
<ul>
<li><a href="#String_to_a_DateTime_object_using_datetime.strptime()">String to a DateTime object using datetime.strptime()</a></li>
<li><a href="#Format_Code_List">Format Code List</a></li>
<li><a href="#How_strptime()_works?">How strptime() works?</a></li>
<li><a href="#Examples_on_converting_a_Time_String_in_the_format_codes_using_strptime()_method">Examples of converting a Time String in the format codes using strptime() method</a></li>
</ul>
<h2><a id="String_to_a_DateTime_object_using_datetime.strptime()"></a>String to a DateTime object using datetime.strptime()</h2>
<p>The<code>strptime()</code>method generates a datetime object from the given string.</p>
<p>Datetime module provides a datetime class that has a method to convert string to a datetime object.</p>
<h3>Syntax:</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">datetime.strptime(date_string, format)</pre>
<p>So in the above syntax, you can see that it accepts a string containing a timestamp. It parses the string according to format codes and returns a datetime object created from it.</p>
<p>First import datetime class from datetime module to use this,</p>
<p><code class="EnlighterJSRAW" data-enlighter-language="generic">from datetime import datetime</code></p>
<p><span style="color: #ff6600;">Also Read:</span></p>
<ul>
<li><a href="https://python-programs.com/python-how-to-remove-characters-from-a-string-by-index/">Python: How to remove characters from a string by Index?</a></li>
<li><a href="https://python-programs.com/convert-integer-to-string-in-python/">Convert integer to string in Python</a></li>
</ul>
<h2><a id="Format_Code_List"></a>Complete Format Code List</h2>
<table border="1">
<tbody>
<tr>
<th>Format Codes</th>
<th>Description</th>
<th>Example</th>
</tr>
<tr>
<td>%d</td>
<td>Day of the month as a zero-padded decimal number</td>
<td>01, 02, 03, 04 …, 31</td>
</tr>
<tr>
<td>%a</td>
<td>Weekday as the abbreviated name</td>
<td>Sun, Mon, …, Sat</td>
</tr>
<tr>
<td>%A</td>
<td>Weekday as full name</td>
<td>Sunday, Monday, …, Saturday</td>
</tr>
<tr>
<td>%m</td>
<td>Month as a zero-padded decimal number</td>
<td>01, 02, 03, 04 …, 12</td>
</tr>
<tr>
<td>%b</td>
<td>Month as an abbreviated name</td>
<td>Jan, Feb, …, Dec</td>
</tr>
<tr>
<td>%B</td>
<td>Month as full name</td>
<td>January, February, …, December</td>
</tr>
<tr>
<td>%y</td>
<td>A Year without century as a zero-padded decimal number</td>
<td>00, 01, …, 99</td>
</tr>
<tr>
<td>%Y</td>
<td>A Year with a century as a decimal number</td>
<td>0001, …, 2018, …, 9999</td>
</tr>
<tr>
<td>%H</td>
<td>Hour (24-hour clock) as a zero-padded decimal number</td>
<td>01, 02, 03, 04 …, 23</td>
</tr>
<tr>
<td>%M</td>
<td>Minute as a zero-padded decimal number</td>
<td>01, 02, 03, 04 …, 59</td>
</tr>
<tr>
<td>%S</td>
<td>Second as a zero-padded decimal number</td>
<td>01, 02, 03, 04 …, 59</td>
</tr>
<tr>
<td>%f</td>
<td>Microsecond as a decimal number, zero-padded on the left</td>
<td>000000, 000001, …, 999999</td>
</tr>
<tr>
<td>%I</td>
<td>Hour (12-hour clock) as a zero-padded decimal number</td>
<td>01, 02, 03, 04 …, 12</td>
</tr>
<tr>
<td>%p</td>
<td>Locale’s equivalent of either AM or PM</td>
<td>AM, PM</td>
</tr>
<tr>
<td>%j</td>
<td>Day of the year as a zero-padded decimal number</td>
<td>01, 02, 03, 04 …, 366</td>
</tr>
</tbody>
</table>
<h2><a id="How_strptime()_works?"></a>How strptime() works?</h2>
<p>In the<code>strptime()</code>class method, it takes two arguments:</p>
<ul>
<li>string (that be converted to datetime)</li>
<li>format code</li>
</ul>
<p>In the accordance with the string and format code used, the method returns its equivalent datetime object.</p>
<p>Let&#8217;s see the following example, to understand how it works:</p>
<p><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-6506" src="https://python-programs.com/wp-content/uploads/2021/05/python-strptime-method-example.png" alt="python strptime method example" width="491" height="104" srcset="https://python-programs.com/wp-content/uploads/2021/05/python-strptime-method-example.png 491w, https://python-programs.com/wp-content/uploads/2021/05/python-strptime-method-example-300x64.png 300w" sizes="(max-width: 491px) 100vw, 491px" /></p>
<p>where,</p>
<p><code>%d</code> &#8211; Represents the day of the month. Example: 01, 02, &#8230;, 31<br />
<code>%B</code> &#8211; Month&#8217;s name in full. Example: January, February etc.<br />
<code>%Y</code> &#8211; Year in four digits. Example: 2018, 2019 etc.</p>
<h2><a id="Examples_of_converting_a_Time_String_in_the_format_codes_using_strptime()_method"></a>Examples of converting a Time String in the format codes using strptime() method</h2>
<p>Just have a look at the few examples on how to convert timestamp string to a datetime object using datetime.strptime() in Python and gain enough knowledge on it.</p>
<h3>Example 1:</h3>
<p>Let&#8217;s take an example,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">from datetime import datetime
datetimeObj = datetime.strptime('2021-05-17T15::11::45.456777', '%Y-%m-%dT%H::%M::%S.%f')
print(datetimeObj)
print(type(datetimeObj))</pre>
<p><strong>Output:</strong></p>
<pre>2021-05-17 15:11:45.456777
&lt;class 'datetime.datetime'&gt;
</pre>
<p>So in the above example, you can see that we have converted a time string in the format <strong>&#8220;YYYY-MM-DDTHH::MM::SS.MICROS&#8221;</strong> to a DateTime object.</p>
<p>Let&#8217;s take another example,</p>
<h3>Example 2:</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">from datetime import datetime
datetimeObj = datetime.strptime('17/May/2021 14:12:22', '%d/%b/%Y %H:%M:%S')
print(datetimeObj)
print(type(datetimeObj))</pre>
<p><strong>Output:</strong></p>
<pre>2021-05-17 14:12:22
&lt;class 'datetime.datetime'&gt;
</pre>
<p>So this is the other way to show timestamp here we have converted a time string in the format<strong> &#8220;DD/MM/YYYY HH::MM::SS&#8221;</strong> to a datetime object.</p>
<h3>Example 3:</h3>
<p>If we want to show the only date in this format &#8220;DD MMM YYYY&#8221;. We do like this,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">from datetime import datetime
datetimeObj = datetime.strptime('17 May 2021', '%d %b %Y')
# Get the date object from datetime object
dateObj = datetimeObj.date()
print(dateObj)
print(type(dateObj))</pre>
<p><strong>Output:</strong></p>
<pre>2021-05-17
&lt;class 'datetime.date'&gt;

</pre>
<h3>Example 4:</h3>
<p>So if we want to show only time &#8220;‘HH:MM:SS AP‘&#8221; in this format. We will do like that,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">from datetime import datetime
datetimeObj = datetime.strptime('08:12:22 PM', '%I:%M:%S %p') 
# Get the time object from datetime object 
timeObj = datetimeObj.time()
print(timeObj) 
print(type(timeObj))</pre>
<p><strong>Output:</strong></p>
<pre>20:12:22
&lt;class 'datetime.time'&gt;
</pre>
<h3>Example 5:</h3>
<p>If we want to show our timestamp in text format. We will execute like that,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">from datetime import datetime
textStr = "On January the 17th of 2021 meet me at 8 PM"
datetimeObj = datetime.strptime(textStr, "On %B the %dth of %Y meet me at %I %p")
print(datetimeObj)</pre>
<p><strong>Output:</strong></p>
<pre>2021-01-17 20:00:00
</pre>
<h3>Conclusion:</h3>
<p>So in the above tutorial, you can see that we have shown different methods of how to convert a timestamp string to a datetime object using datetime.strptime(). Thank you!</p>
<p>The post <a href="https://python-programs.com/python-how-to-convert-a-timestamp-string-to-a-datetime-object-using-datetime-strptime/">Python: How to convert a timestamp string to a datetime object using datetime.strptime()</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6315</post-id>	</item>
		<item>
		<title>Pandas: Select first or last N rows in a Dataframe using head() &#038; tail()</title>
		<link>https://python-programs.com/pandas-select-first-or-last-n-rows-in-a-dataframe-using-head-tail/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Sun, 29 Oct 2023 11:26:29 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=6093</guid>

					<description><![CDATA[<p>In this tutorial, we are going to discuss how to select the first or last N rows in a Dataframe using head() &#38; tail() functions. This guide describes the following contents. Select first N Rows from a Dataframe using head() function Select first N rows from the dataframe with specific columns Select last N Rows [&#8230;]</p>
<p>The post <a href="https://python-programs.com/pandas-select-first-or-last-n-rows-in-a-dataframe-using-head-tail/">Pandas: Select first or last N rows in a Dataframe using head() &#038; tail()</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this tutorial, we are going to discuss how to select the first or last N rows in a Dataframe using head() &amp; tail() functions. This guide describes the following contents.</p>
<ul>
<li><a href="#Select_first_N_Rows_from_a_Dataframe_using_head()_function">Select first N Rows from a Dataframe using head() function</a></li>
<li><a href="#Select_first_N_rows_from_the_dataframe_with_specific_columns">Select first N rows from the dataframe with specific columns</a></li>
<li><a href="#Select_last_N_Rows_from_a_Dataframe_using_tail()_function">Select last N Rows from a Dataframe using tail() function</a></li>
<li><a href="#Select_bottom_N_rows_from_the_dataframe_with_specific_columns">Select bottom N rows from the dataframe with specific columns</a></li>
</ul>
<h2><a id="Select_first_N_Rows_from_a_Dataframe_using_head()_function"></a>Select first N Rows from a Dataframe using head() function</h2>
<h3>pandas.DataFrame.head()</h3>
<p>In Python&#8217;s Pandas module, the Dataframe class gives the head() function to fetch top rows from it.</p>
<p><strong>Syntax:</strong></p>
<p><code class="EnlighterJSRAW" data-enlighter-language="generic">DataFrame.head(self, n=5)</code></p>
<p>If we give some value to n it will return n number of rows otherwise default is 5.</p>
<p>Let&#8217;s create a dataframe first,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
empoyees = [('Ram', 34, 'Sunderpur', 5) ,
           ('Riti', 31, 'Delhi' , 7) ,
           ('Aman', 16, 'Thane', 9) ,
           ('Shishir', 41,'Delhi' , 12) ,
           ('Veeru', 33, 'Delhi' , 4) ,
           ('Shan',35,'Mumbai', 5 ),
           ('Shikha', 35, 'kolkata', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
print("Contents of the Dataframe : ")
print(empDfObj)</pre>
<p><strong>Output:</strong></p>
<pre>Contents of the Dataframe :
     Name  Age  City           Experience
a   Ram     34   Sunderpur 5
b   Riti       31  Delhi          7
c   Aman   16  Thane         9
d  Shishir   41 Delhi          12
e  Veeru     33 Delhi          4
f   Shan      35 Mumbai     5
g  Shikha   35 kolkata      11

</pre>
<p>So if we want to select the top 4 rows from the dataframe,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
empoyees = [('Ram', 34, 'Sunderpur', 5) ,
           ('Riti', 31, 'Delhi' , 7) ,
           ('Aman', 16, 'Thane', 9) ,
           ('Shishir', 41,'Delhi' , 12) ,
           ('Veeru', 33, 'Delhi' , 4) ,
           ('Shan',35,'Mumbai', 5 ),
           ('Shikha', 35, 'kolkata', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

dfObj1 = empDfObj.head(4)
print("First 4 rows of the Dataframe : ")
print(dfObj1)</pre>
<p><strong>Output:</strong></p>
<pre>First 4 rows of the Dataframe :
  Name    Age   City         Experience
a Ram      34     Sunderpur 5
b Riti        31    Delhi          7
c Aman    16    Thane        9
d Shishir   41   Delhi         12

</pre>
<p>So in the above example, you can see that we have given n value 4 so it returned the top 4 rows from the dataframe.</p>
<p><span style="color: #ff6600;">Do Check:</span></p>
<ul>
<li><a href="https://python-programs.com/python-numpy-flatten-function-tutorial-with-examples/">Python: numpy.flatten() – Function Tutorial with examples</a></li>
<li><a href="https://python-programs.com/python-add-column-to-dataframe-in-pandas-based-on-other-column-or-list-or-default-value/">Python: Add column to dataframe in Pandas ( based on other column or list or default value)</a></li>
</ul>
<h3><a id="Select_first_N_rows_from_the_dataframe_with_specific_columns"></a>Select first N rows from the dataframe with specific columns</h3>
<p>In this, while selecting the first 3 rows, we can select specific columns too,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
empoyees = [('Ram', 34, 'Sunderpur', 5) ,
           ('Riti', 31, 'Delhi' , 7) ,
           ('Aman', 16, 'Thane', 9) ,
           ('Shishir', 41,'Delhi' , 12) ,
           ('Veeru', 33, 'Delhi' , 4) ,
           ('Shan',35,'Mumbai', 5 ),
           ('Shikha', 35, 'kolkata', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# Select the top 3 rows of the Dataframe for 2 columns only
dfObj1 = empDfObj[['Name', 'City']].head(3)
print("First 3 rows of the Dataframe for 2 columns : ")
print(dfObj1)
</pre>
<p><strong>Output:</strong></p>
<pre>First 3 rows of the Dataframe for 2 columns :
   Name  City
a Ram    Sunderpur
b Riti      Delhi
c Aman  Thane
</pre>
<h3><a id="Select_last_N_Rows_from_a_Dataframe_using_tail()_function"></a>Select last N Rows from a Dataframe using tail() function</h3>
<p>In the Pandas module, the Dataframe class provides a tail() function to select bottom rows from a Dataframe.</p>
<p>Syntax:</p>
<p><code class="EnlighterJSRAW" data-enlighter-language="generic">DataFrame.tail(self, n=5)</code></p>
<p>It will return the last n rows from a dataframe. If n is not provided then the default value is 5. So for this, we are going to use the above dataframe as an example,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
empoyees = [('Ram', 34, 'Sunderpur', 5) ,
           ('Riti', 31, 'Delhi' , 7) ,
           ('Aman', 16, 'Thane', 9) ,
           ('Shishir', 41,'Delhi' , 12) ,
           ('Veeru', 33, 'Delhi' , 4) ,
           ('Shan',35,'Mumbai', 5 ),
           ('Shikha', 35, 'kolkata', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# Select the last 4 rows of the Dataframe
dfObj1 = empDfObj.tail(4)
print("Last 4 rows of the Dataframe : ")
print(dfObj1)</pre>
<p><strong>Output:</strong></p>
<pre>Last 5 rows of the Dataframe :
  Name     Age City    Experience
d Shishir   41   Delhi      12
e Veeru    33   Delhi       4
f Shan      35   Mumbai  5
g Shikha  35   kolkata    11

</pre>
<p>So in above example, you can see that we are given n value 4 so tail() function return last 4 data value.</p>
<h3><a id="Select_bottom_N_rows_from_the_dataframe_with_specific_columns"></a>Select bottom N rows from the dataframe with specific columns</h3>
<p>In this, while selecting the last 4 rows, we can select specific columns too,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
empoyees = [('Ram', 34, 'Sunderpur', 5) ,
           ('Riti', 31, 'Delhi' , 7) ,
           ('Aman', 16, 'Thane', 9) ,
           ('Shishir', 41,'Delhi' , 12) ,
           ('Veeru', 33, 'Delhi' , 4) ,
           ('Shan',35,'Mumbai', 5 ),
           ('Shikha', 35, 'kolkata', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# Select the bottom 4 rows of the Dataframe for 2 columns only
dfObj1 = empDfObj[['Name', 'City']].tail(4)
print("Last 4 rows of the Dataframe for 2 columns : ")
print(dfObj1)
</pre>
<p><strong>Output:</strong></p>
<pre>Last 4 rows of the Dataframe for 2 columns :
     Name   City
d  Shishir  Delhi
e  Veeru    Delhi
f   Shan     Mumbai
g  Shikha   kolkata
</pre>
<h3>Conclusion:</h3>
<p>In this article, you have seen how to select first or last N  rows in a Dataframe using head() &amp; tail() functions. Thank you!</p>
<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 – Select items from a Dataframe</strong></p>
<ul>
<li><a href="https://python-programs.com/select-rows-columns-by-name-or-index-in-dataframe-using-loc-iloc-python-pandas/">Select Rows &amp; Columns in a Dataframe using loc &amp; iloc in</a></li>
<li><a href="https://python-programs.com/select-rows-columns-by-name-or-index-in-dataframe-using-loc-iloc-python-pandas/">Select Rows in a Dataframe based on conditions</a></li>
<li><a href="https://python-programs.com/pandas-dataframe-get-minimum-values-in-rows-or-columns-their-index-position/">Get minimum values in rows or columns &amp; their index position in Dataframe</a></li>
<li><a href="https://python-programs.com/pandas-get-unique-values-in-columns-of-a-dataframe-in-python/">Get unique values in columns of a Dataframe</a></li>
<li><a href="https://python-programs.com/get-rows-and-columns-names-in-dataframe-using-python/">Get a list of column and row names in a DataFrame</a></li>
<li><a href="https://python-programs.com/pandas-convert-a-dataframe-into-a-list-of-rows-or-columns-in-python-list-of-lists/">Get DataFrame contents as a list of rows or columns (list of lists)</a></li>
</ul>
<p>The post <a href="https://python-programs.com/pandas-select-first-or-last-n-rows-in-a-dataframe-using-head-tail/">Pandas: Select first or last N rows in a Dataframe using head() &#038; tail()</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6093</post-id>	</item>
		<item>
		<title>Pandas: Find maximum values &#038; position in columns or rows of a Dataframe &#124; How to find the max value of a pandas DataFrame column in Python?</title>
		<link>https://python-programs.com/pandas-find-maximum-values-position-in-columns-or-rows-of-a-dataframe/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Sun, 29 Oct 2023 10:11:43 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=5943</guid>

					<description><![CDATA[<p>In this article, we will discuss how to find maximum value &#38; position in rows or columns of a Dataframe and its index position. DataFrame.max() Syntax Get maximum values in every row &#38; column of the Dataframe Get maximum values of every column Get maximum values of every row Get maximum values of every column [&#8230;]</p>
<p>The post <a href="https://python-programs.com/pandas-find-maximum-values-position-in-columns-or-rows-of-a-dataframe/">Pandas: Find maximum values &#038; position in columns or rows of a Dataframe | How to find the max value of a pandas DataFrame column in Python?</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this article, we will discuss how to find maximum value &amp; position in rows or columns of a Dataframe and its index position.</p>
<ul>
<li><a href="#DataFrame.max()">DataFrame.max()</a></li>
<li><a href="#Syntax">Syntax</a></li>
<li><a href="#Get_maximum_values_in_every_row_&amp;_column_of_the_Dataframe">Get maximum values in every row &amp; column of the Dataframe</a></li>
<li><a href="#Get_maximum_values_of_every_column">Get maximum values of every column</a></li>
<li><a href="#Get_maximum_values_of_every_row">Get maximum values of every row</a></li>
<li><a href="#Get_maximum_values_of_every_column_without_skipping_NaN">Get maximum values of every column without skipping NaN</a></li>
<li><a href="#Get_maximum_values_of_a_single_column_or_selected_columns">Get maximum values of a single column or selected columns</a></li>
<li><a href="#Get_row_index_label_or_position_of_maximum_values_of_every_column">Get row index label or position of maximum values of every column</a></li>
<li><a href="#Get_row_index_label_of_Maximum_value_in_every_column">Get row index label of Maximum value in every column</a></li>
<li><a href="#Get_Column_names_of_Maximum_value_in_every_row">Get Column names of Maximum value in every row</a></li>
</ul>
<h2><a id="DataFrame.max()"></a>DataFrame.max()</h2>
<p>Python pandas provide a member function in the dataframe to find the maximum value.</p>
<h3><a id="Syntax"></a>Syntax:</h3>
<p><code class="EnlighterJSRAW" data-enlighter-language="generic">DataFrame.max(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)</code></p>
<p>Dataframe.max() accepts these arguments:</p>
<p>axis: Where max element will be searched</p>
<p>skipna: Default is True means if not provided it will be skipped.</p>
<p>Let&#8217;s create a dataframe,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
import numpy as np
# List of Tuples
matrix = [(17, 15, 12),
          (53, np.NaN, 10),
          (46, 34, 11),
          (35, 45, np.NaN),
          (76, 26, 13)
          ]
# Create a DataFrame object
dfObj = pd.DataFrame(matrix, index=list('abcde'), columns=list('xyz'))
print(dfObj)</pre>
<p><strong>Output:</strong></p>
<pre>   x             y      z
a 17     15.0   12.0
b 53     NaN   10.0
c 46      34.0   11.0
d 35      45.0   NaN
e 76      26.0   13.0
</pre>
<h2><a id="Get_maximum_values_in_every_row_&amp;_column_of_the_Dataframe"></a>Get maximum values in every row &amp; column of the Dataframe</h2>
<p>Here, you will find two ways to get the maximum values in dataframe</p>
<p><span style="color: #ff6600;">Also Check: </span></p>
<ul>
<li><a href="https://python-programs.com/python-how-to-get-current-date-and-time-or-timestamp/">Python: How to get the current date and time or timestamp?</a></li>
<li><a href="https://python-programs.com/python-find-indexes-of-an-element-in-pandas-dataframe/">Python: Find indexes of an element in pandas dataframe</a></li>
</ul>
<h3><a id="Get_maximum_values_of_every_column"></a>Get maximum values of every column</h3>
<p>In this, we will call the max() function to find the maximum value of every column in DataFrame.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
import numpy as np
# List of Tuples
matrix = [(17, 15, 12),
          (53, np.NaN, 10),
          (46, 34, 11),
          (35, 45, np.NaN),
          (76, 26, 13)
          ]
# Create a DataFrame object
dfObj = pd.DataFrame(matrix, index=list('abcde'), columns=list('xyz'))
# Get a series containing maximum value of each column
maxValuesObj = dfObj.max()
print('Maximum value in each column : ')
print(maxValuesObj)</pre>
<p><strong>Output:</strong></p>
<pre>Maximum value in each column :
x 76.0
y 45.0
z 13.0
</pre>
<h3><a id="Get_maximum_values_of_every_row"></a>Get maximum values of every row</h3>
<p>In this also we will call the max() function to find the maximum value of every row in DataFrame.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
import numpy as np
# List of Tuples
matrix = [(17, 15, 12),
          (53, np.NaN, 10),
          (46, 34, 11),
          (35, 45, np.NaN),
          (76, 26, 13)
          ]
# Create a DataFrame object
dfObj = pd.DataFrame(matrix, index=list('abcde'), columns=list('xyz'))
# Get a series containing maximum value of each row
maxValuesObj = dfObj.max(axis=1)
print('Maximum value in each row : ')
print(maxValuesObj)</pre>
<p><strong>Output:</strong></p>
<pre>Maximum value in each row :
a   17.0
b   53.0
c   46.0
d   45.0
e   76.0

</pre>
<p>So in the above example, you can see that it returned a series with a row index label and maximum value of each row.</p>
<h2><a id="Get_maximum_values_of_every_column_without_skipping_NaN"></a>Get maximum values of every column without skipping NaN</h2>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
import numpy as np
# List of Tuples
matrix = [(17, 15, 12),
          (53, np.NaN, 10),
          (46, 34, 11),
          (35, 45, np.NaN),
          (76, 26, 13)
          ]
# Create a DataFrame object
dfObj = pd.DataFrame(matrix, index=list('abcde'), columns=list('xyz'))
# Get a series containing maximum value of each column without skipping NaN
maxValuesObj = dfObj.max(skipna=False)
print('Maximum value in each column including NaN: ')
print(maxValuesObj)</pre>
<p><strong>Output:</strong></p>
<pre>Maximum value in each column including NaN:
x 76.0
y NaN
z NaN
</pre>
<p>So in the above example, you can see that we have passed the &#8216;skipna=False&#8217; in the max() function, So it included the NaN while searching for NaN.</p>
<p>If there is any NaN in the column then it will be considered as the maximum value of that column.</p>
<h2><a id="Get_maximum_values_of_a_single_column_or_selected_columns"></a>Get maximum values of a single column or selected columns</h2>
<p>So for getting a single column maximum value we have to select that column and apply the max() function in it,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
import numpy as np
# List of Tuples
matrix = [(17, 15, 12),
          (53, np.NaN, 10),
          (46, 34, 11),
          (35, 45, np.NaN),
          (76, 26, 13)
          ]
# Create a DataFrame object
dfObj = pd.DataFrame(matrix, index=list('abcde'), columns=list('xyz'))
# Get maximum value of a single column 'y'
maxValue = dfObj['y'].max()
print("Maximum value in column 'y': " , maxValue)</pre>
<p>Here you can see that we have passed y  <code class="EnlighterJSRAW" data-enlighter-language="generic">maxValue = dfObj['y'].max()</code>for getting max value in that column.</p>
<p><strong>Output:</strong></p>
<pre>Maximum value in column 'y': 45.0
</pre>
<p>We can also pass the list of column names instead of passing single column like.,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
import numpy as np
# List of Tuples
matrix = [(17, 15, 12),
          (53, np.NaN, 10),
          (46, 34, 11),
          (35, 45, np.NaN),
          (76, 26, 13)
          ]
# Create a DataFrame object
dfObj = pd.DataFrame(matrix, index=list('abcde'), columns=list('xyz'))
# Get maximum value of a single column 'y'
maxValue = dfObj[['y', 'z']].max()
print("Maximum value in column 'y' &amp; 'z': ")
print(maxValue)</pre>
<p><strong>Output:</strong></p>
<pre>Maximum value in column 'y' &amp; 'z':
y 45.0
z 13.0
</pre>
<h2><a id="Get_row_index_label_or_position_of_maximum_values_of_every_column"></a>Get row index label or position of maximum values of every column</h2>
<h3>DataFrame.idxmax()</h3>
<p>So in the above examples, you have seen how to get the max value of rows and columns but what if we want to know the index position of that row and column whereas the value is maximum, by using dataframe.idxmax() we get the index position.</p>
<p>Syntax-</p>
<p><code class="EnlighterJSRAW" data-enlighter-language="generic">DataFrame.idxmax(axis=0, skipna=True)</code></p>
<h2><a id="Get_row_index_label_of_Maximum_value_in_every_column"></a>Get row index label of Maximum value in every column</h2>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
import numpy as np
# List of Tuples
matrix = [(17, 15, 12),
          (53, np.NaN, 10),
          (46, 34, 11),
          (35, 45, np.NaN),
          (76, 26, 13)
          ]
# Create a DataFrame object
dfObj = pd.DataFrame(matrix, index=list('abcde'), columns=list('xyz'))
# get the index position of max values in every column
maxValueIndexObj = dfObj.idxmax()
print("Max values of columns are at row index position :")
print(maxValueIndexObj)
</pre>
<p><strong>Output:</strong></p>
<pre>Max values of columns are at row index position :
x e
y d
z e
dtype: object
</pre>
<p>So here you have seen it showed the index position of the column where max value exists.</p>
<h2><a id="Get_Column_names_of_Maximum_value_in_every_row"></a>Get Column names of Maximum value in every row</h2>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
import numpy as np
# List of Tuples
matrix = [(17, 15, 12),
          (53, np.NaN, 10),
          (46, 34, 11),
          (35, 45, np.NaN),
          (76, 26, 13)
          ]
# Create a DataFrame object
dfObj = pd.DataFrame(matrix, index=list('abcde'), columns=list('xyz'))
# get the column name of max values in every row
maxValueIndexObj = dfObj.idxmax(axis=1)
print("Max values of row are at following columns :")
print(maxValueIndexObj)</pre>
<p><strong>Output:</strong></p>
<pre>Max values of row are at following columns :
a x
b x
c x
d y
e x
dtype: object
</pre>
<p>So here you have seen it showed the index position of a row where max value exists.</p>
<h3>Conclusion:</h3>
<p>So in this article, we have seen how to find maximum value &amp; position in rows or columns of a Dataframe and its index position. Thank you!</p>
<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 – Find Elements in a Dataframe</strong></p>
<ul>
<li><a href="https://python-programs.com/pandas-check-if-a-value-exists-in-a-dataframe-using-in-not-in-operator-isin/">Check if a value exists in a DataFrame using in &amp; not in operator | isin()</a></li>
<li><a href="https://python-programs.com/pandas-sort-rows-or-columns-in-dataframe-based-on-values-using-dataframe-sort_values/">Find &amp; Drop duplicate columns in a DataFrame</a></li>
<li><a href="https://python-programs.com/pandas-4-ways-to-check-if-a-dataframe-is-empty-in-python/">Check if a DataFrame is empty in Python</a></li>
<li><a href="https://python-programs.com/pandas-find-duplicate-rows-in-a-dataframe-based-on-all-or-selected-columns-using-dataframe-duplicated-in-python/">Find duplicate rows in a Dataframe based on all or selected columns using DataFrame.duplicated() in Python</a></li>
<li><a href="https://python-programs.com/python-find-indexes-of-an-element-in-pandas-dataframe/">Find indexes of an element in pandas dataframe</a></li>
</ul>
<p>The post <a href="https://python-programs.com/pandas-find-maximum-values-position-in-columns-or-rows-of-a-dataframe/">Pandas: Find maximum values &#038; position in columns or rows of a Dataframe | How to find the max value of a pandas DataFrame column 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">5943</post-id>	</item>
		<item>
		<title>Python: Add column to dataframe in Pandas ( based on other column or list or default value)</title>
		<link>https://python-programs.com/python-add-column-to-dataframe-in-pandas-based-on-other-column-or-list-or-default-value/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Sat, 28 Oct 2023 13:38:27 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=5220</guid>

					<description><![CDATA[<p>In this tutorial, we are going to discuss different ways to add columns to the dataframe in pandas. Moreover, you can have an idea about the Pandas Add Column, Adding a new column to the existing DataFrame in Pandas and many more from the below explained various methods. Pandas Add Column Add column to dataframe [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-add-column-to-dataframe-in-pandas-based-on-other-column-or-list-or-default-value/">Python: Add column to dataframe in Pandas ( based on other column or list or default value)</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this tutorial, we are going to discuss different ways to add columns to the dataframe in pandas. Moreover, you can have an idea about the Pandas Add Column, Adding a new column to the existing DataFrame in Pandas and many more from the below explained various methods.</p>
<ul>
<li><a href="#Pandas_Add_Column">Pandas Add Column</a></li>
<li><a href="#Add_column_to_dataframe_in_pandas_using_[]_operator">Add column to dataframe in pandas using [] operator</a></li>
<li><a href="#Add_new_column_to_DataFrame_with_same_default_value">Add new column to DataFrame with same default value</a></li>
<li><a href="#Add_column_based_on_another_column">Add column based on another column</a></li>
<li><a href="#Append_column_to_dataFrame_using_assign()_function">Append column to dataFrame using assign() function</a></li>
<li><a href="#Add_a_columns_in_DataFrame_based_on_other_column_using_lambda_function">Add a columns in DataFrame based on other column using lambda function</a></li>
<li><a href="#Add_new_column_to_Dataframe_using_insert()">Add new column to Dataframe using insert()</a></li>
<li><a href="#Add_a_column_to_Dataframe_by_dictionary">Add a column to Dataframe by dictionary</a></li>
</ul>
<h2><a id="Pandas_Add_Column"></a>Pandas Add Column</h2>
<p>Pandas is one such data analytics library created explicitly for Python to implement data manipulation and data analysis. The Pandas library made of specific data structures and operations to deal with numerical tables, analyzing data, and work with time series.</p>
<p>Basically, there are three ways to add columns to pandas i.e., Using [] operator, using assign() function &amp; using insert().</p>
<p>We will discuss it all one by one.</p>
<p>First, let&#8217;s create a dataframe object,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students,
                      columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])
print(df_obj )</pre>
<p><strong>Output:</strong></p>
<pre>    Name    Age  City        Country
a  Rakesh  34     Agra        India
b  Rekha   30     Pune        India
c  Suhail    31    Mumbai   India
d  Neelam 32   Bangalore India
e  Jay         16   Bengal      India
f  Mahak    17  Varanasi     India
</pre>
<p><span style="color: #ff6600;">Do Check:</span></p>
<ul>
<li><a href="https://python-programs.com/https-python-programs.com-pandas-skip-rows-while-reading-csv-file-to-a-dataframe-using-read_csv-in-python/">Pandas: Delete last column of dataframe in python</a></li>
<li><a href="https://python-programs.com/pandas-loop-or-iterate-over-all-or-certain-columns-of-a-dataframe/">Pandas: Loop or Iterate over all or certain columns of a dataframe</a></li>
</ul>
<h3><a id="Add_column_to_dataframe_in_pandas_using_[]_operator"></a>Add column to dataframe in pandas using [] operator</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students,
                      columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])

# Add column with Name Score
df_obj['Score'] = [10, 20, 45, 33, 22, 11]
print(df_obj )</pre>
<p><strong>Output:</strong></p>
<pre>      Name     Age   City        Country   Score
a    Rakesh    34    Agra          India      10
b    Rekha     30    Pune          India      20
c    Suhail     31     Mumbai    India      45
d    Neelam  32    Bangalore  India      33
e    Jay         16     Bengal       India      22
f    Mahak    17    Varanasi     India       11

</pre>
<p>So in the above example, you have seen we have added one extra column &#8216;score&#8217; in our dataframe. So in this, we add a new column to Dataframe with Values in the list. In the above dataframe, there is no column name &#8216;score&#8217; that&#8217;s why it added if there is any column with the same name that already exists then it will replace all its values.</p>
<h3><a id="Add_new_column_to_DataFrame_with_same_default_value"></a>Add new column to DataFrame with same default value</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students,
                      columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])

df_obj['Total'] = 100
print(df_obj)</pre>
<p><strong>Output:</strong></p>
<pre>         Name    Age    City     Country      Total
a       Rakesh   34    Agra       India          100
b       Rekha    30    Pune       India          100
c       Suhail     31   Mumbai  India          100
d       Neelam  32  Bangalore India        100
e       Jay          16  Bengal       India        100
f       Mahak     17 Varanasi     India        100
</pre>
<p>So in the above example, we have added a new column ‘Total’ with the same value of 100 in each index.</p>
<h3><a id="Add_column_based_on_another_column"></a>Add column based on another column</h3>
<p>Let’s add a new column ‘Percentage‘ where entrance at each index will be added by the values in other columns at that index i.e.,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">df_obj['Percentage'] = (df_obj['Marks'] / df_obj['Total']) * 100
df_obj</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">    Name  Age       City    Country  Marks  Total  Percentage
a   jack   34     Sydeny  Australia     10     50        20.0
b   Riti   30      Delhi      India     20     50        40.0
c  Vikas   31     Mumbai      India     45     50        90.0
d  Neelu   32  Bangalore      India     33     50        66.0
e   John   16   New York         US     22     50        44.0
f   Mike   17  las vegas         US     11     50        22.0</pre>
<h3><a id="Append_column_to_dataFrame_using_assign()_function"></a>Append column to dataFrame using assign() function</h3>
<p>So for this, we are going to use the same dataframe which we have created in starting.</p>
<p><strong>Syntax:</strong></p>
<p><code class="EnlighterJSRAW" data-enlighter-language="generic">DataFrame.assign(**kwargs)</code></p>
<p>Let’s add columns in DataFrame using assign().</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students,
                      columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])
mod_fd = df_obj.assign(Marks=[10, 20, 45, 33, 22, 11])
print(mod_fd)
</pre>
<p><strong>Output:</strong></p>
<p><img decoding="async" class="alignnone size-full wp-image-5289" src="https://python-programs.com/wp-content/uploads/2021/05/Add-a-column-using-assign.png" alt="Add-a-column-using-assign" width="527" height="185" srcset="https://python-programs.com/wp-content/uploads/2021/05/Add-a-column-using-assign.png 527w, https://python-programs.com/wp-content/uploads/2021/05/Add-a-column-using-assign-300x105.png 300w" sizes="(max-width: 527px) 100vw, 527px" /></p>
<p>It will return a new dataframe with a new column ‘Marks’ in that Dataframe. Values provided in the list will be used as column values.</p>
<h3><a id="Add_a_columns_in_DataFrame_based_on_other_column_using_lambda_function"></a><a id="Add_a_columns_in_DataFrame_based_on_other_column_using_lambda_function"></a>Add column in DataFrame based on other column using lambda function</h3>
<p>In this method using two existing columns i.e, score and total value we are going to create a new column i.e..&#8217; percentage&#8217;.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])
df_obj['Score'] = [10, 20, 45, 33, 22, 11]
df_obj['Total'] = 100
df_obj = df_obj.assign(Percentage=lambda x: (x['Score'] / x['Total']) * 100)
print(df_obj)
</pre>
<p><strong>Output:</strong></p>
<p><img decoding="async" class="alignnone size-full wp-image-5288" src="https://python-programs.com/wp-content/uploads/2021/05/Add-column-based-on-another-column.png" alt="Add-column-based-on-another-column" width="795" height="223" srcset="https://python-programs.com/wp-content/uploads/2021/05/Add-column-based-on-another-column.png 795w, https://python-programs.com/wp-content/uploads/2021/05/Add-column-based-on-another-column-300x84.png 300w, https://python-programs.com/wp-content/uploads/2021/05/Add-column-based-on-another-column-768x215.png 768w" sizes="(max-width: 795px) 100vw, 795px" /></p>
<h3><a id="Add_new_column_to_Dataframe_using_insert()"></a>Add new column to Dataframe using insert()</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])
# Insert column at the 2nd position of Dataframe
df_obj.insert(2, "Marks", [10, 20, 45, 33, 22, 11], True)
print(df_obj)
</pre>
<p><strong>Output:</strong></p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-5292" src="https://python-programs.com/wp-content/uploads/2021/05/add-a-column-using-insert.png" alt="add-a-column-using-insert" width="494" height="166" srcset="https://python-programs.com/wp-content/uploads/2021/05/add-a-column-using-insert.png 494w, https://python-programs.com/wp-content/uploads/2021/05/add-a-column-using-insert-300x101.png 300w" sizes="(max-width: 494px) 100vw, 494px" /></p>
<p>&nbsp;</p>
<p>In other examples, we have added a new column at the end of the dataframe, but in the above example, we insert a new column in between the other columns of the dataframe, then we can use the insert() function.</p>
<h3><a id="Add_a_column_to_Dataframe_by_dictionary"></a>Add a column to Dataframe by dictionary</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])
ids = [11, 12, 13, 14, 15, 16]
# Provide 'ID' as the column name and for values provide dictionary
df_obj['ID'] = dict(zip(ids, df_obj['Name']))
print(df_obj)
</pre>
<p><strong>Output:</strong></p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-5293" src="https://python-programs.com/wp-content/uploads/2021/05/Add-a-column-using-dictionary.png" alt="Add-a-column-using-dictionary" width="494" height="159" srcset="https://python-programs.com/wp-content/uploads/2021/05/Add-a-column-using-dictionary.png 494w, https://python-programs.com/wp-content/uploads/2021/05/Add-a-column-using-dictionary-300x97.png 300w" sizes="(max-width: 494px) 100vw, 494px" /></p>
<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 – Add Contents to a Dataframe</strong></p>
<ul>
<li><a href="https://python-programs.com/append-add-row-to-dataframe-in-pandas/">How to add rows in a DataFrame</a></li>
</ul>
<p>The post <a href="https://python-programs.com/python-add-column-to-dataframe-in-pandas-based-on-other-column-or-list-or-default-value/">Python: Add column to dataframe in Pandas ( based on other column or list or default value)</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5220</post-id>	</item>
		<item>
		<title>Pandas : Loop or Iterate over all or certain columns of a dataframe</title>
		<link>https://python-programs.com/pandas-loop-or-iterate-over-all-or-certain-columns-of-a-dataframe/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Sat, 28 Oct 2023 12:27:39 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=4953</guid>

					<description><![CDATA[<p>In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame. Also, you may learn and understand what is dataframe and how pandas dataframe iterate over columns with the help of great explanations and example codes. About DataFrame Using DataFrame.iteritems() Iterate over columns in dataframe using Column Names [&#8230;]</p>
<p>The post <a href="https://python-programs.com/pandas-loop-or-iterate-over-all-or-certain-columns-of-a-dataframe/">Pandas : Loop or Iterate over all or certain columns of a dataframe</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame. Also, you may learn and understand what is dataframe and how pandas dataframe iterate over columns with the help of great explanations and example codes.</p>
<ul>
<li><a href="#About_DataFrame">About DataFrame</a></li>
<li><a href="#Using_DataFrame.iteritems()">Using DataFrame.iteritems()</a></li>
<li><a href="#Iterate_over_columns_in_dataframe_using_Column_Names">Iterate over columns in dataframe using Column Names</a></li>
<li><a href="#Iterate_over_columns_in_the_dataframe_in_reverse_order">Iterate over columns in the dataframe in reverse order</a></li>
<li><a href="#Iterate_Over_columns_in_dataframe_by_index_using_iloc[]">Iterate Over columns in dataframe by index using iloc[]</a></li>
</ul>
<h2><a id="About_DataFrame"></a>About DataFrame</h2>
<p>A Pandas DataFrame is a 2-dimensional data structure, like a 2-dimensional array, or a table with rows and columns.</p>
<p>First, we are going to create a dataframe that will use in our article.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import pandas as pd

employees = [('Abhishek', 34, 'Sydney') ,
           ('Sumit', 31, 'Delhi') ,
           ('Sampad', 16, 'New York') ,
           ('Shikha', 32,'Delhi') ,
            ]

#load data into a DataFrame object:
df = pd.DataFrame(employees, columns=['Name', 'Age', 'City'], index=['a', 'b', 'c', 'd'])

print(df)</pre>
<p><strong>Output:</strong></p>
<pre>    Name       Age    City
a  Abhishek  34    Sydney
b  Sumit       31    Delhi
c  Sampad   16     New York
d  Shikha     32     Delhi
</pre>
<p><span style="color: #ff6600;">Also Check:</span></p>
<ul>
<li><a href="https://python-programs.com/pandas-skip-rows-while-reading-csv-file-to-a-dataframe-using-read_csv-in-python/"><span data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Pandas : skip rows while reading csv file to a Dataframe using read_csv() in Python&quot;}" data-sheets-userformat="{&quot;2&quot;:897,&quot;3&quot;:{&quot;1&quot;:0},&quot;10&quot;:1,&quot;11&quot;:4,&quot;12&quot;:0}">Pandas: skip rows while reading csv file to a Dataframe using read_csv() in Python</span></a></li>
<li><a href="https://python-programs.com/pandas-convert-a-dataframe-column-into-a-list-using-series-to_list-or-numpy-ndarray-tolist-in-python/">Pandas: Convert a dataframe column into a list using Series.to_list() or numpy.ndarray.tolist() in python</a></li>
</ul>
<h3><a id="Using_DataFrame.iteritems()"></a>Using DataFrame.iteritems()</h3>
<p>We are going to iterate columns of a dataframe using DataFrame.iteritems().</p>
<p>Dataframe class provides a member function iteritems().</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
employees = [('Abhishek', 34, 'Sydney') ,
             ('Sumit', 31, 'Delhi') ,
             ('Sampad', 16, 'New York') ,
             ('Shikha', 32,'Delhi') , ]
#load data into a DataFrame object:
df = pd.DataFrame(employees, columns=['Name', 'Age', 'City'], index=['a', 'b', 'c', 'd'])
# Yields a tuple of column name and series for each column in the dataframe
for (columnName, columnData) in df.iteritems():
   print('Colunm Name : ', columnName)
   print('Column Contents : ', columnData.values)

</pre>
<p><strong>Output:</strong></p>
<pre>Colunm Name : Name
Column Contents : ['Abhishek' 'Sumit' 'Sampad' 'Shikha']
Colunm Name : Age
Column Contents : [34 31 16 32]
Colunm Name : City
Column Contents : ['Sydney' 'Delhi' 'New York' 'Delhi']
</pre>
<p>In the above example, we have to return an iterator that can be used to iterate over all the columns. For each column, it returns a tuple containing the column name and column contents.</p>
<h3><a id="Iterate_over_columns_in_dataframe_using_Column_Names"></a>Iterate over columns in dataframe using Column Names</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
employees = [('Abhishek', 34, 'Sydney') ,
             ('Sumit', 31, 'Delhi') ,
             ('Sampad', 16, 'New York') ,
             ('Shikha', 32,'Delhi') , ]
#load data into a DataFrame object:
df = pd.DataFrame(employees, columns=['Name', 'Age', 'City'], index=['a', 'b', 'c', 'd'])
# Yields a tuple of column name and series for each column in the dataframe
for column in df:
   # Select column contents by column name using [] operator
   columnSeriesObj = df[column]
   print('Colunm Name : ', column)
   print('Column Contents : ', columnSeriesObj.values)
</pre>
<p><strong>Output:</strong></p>
<pre>Colunm Name : Name
Column Contents : ['Abhishek' 'Sumit' 'Sampad' 'Shikha']
Colunm Name : Age
Column Contents : [34 31 16 32]
Colunm Name : City
Column Contents : ['Sydney' 'Delhi' 'New York' 'Delhi']
</pre>
<p>ln the above example, we can see that <code class="EnlighterJSRAW" data-enlighter-language="generic">Dataframe.columns</code> returns a sequence of column names on which we put iteration and return column name and content.</p>
<h3><a id="Iterate_over_columns_in_the_dataframe_in_reverse_order"></a>Iterate Over columns in dataframe in reverse order</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
employees = [('Abhishek', 34, 'Sydney') ,
             ('Sumit', 31, 'Delhi') ,
             ('Sampad', 16, 'New York') ,
             ('Shikha', 32,'Delhi') , ]
#load data into a DataFrame object:
df = pd.DataFrame(employees, columns=['Name', 'Age', 'City'], index=['a', 'b', 'c', 'd'])
# Yields a tuple of column name and series for each column in the dataframe
for column in reversed(df.columns):
   # Select column contents by column name using [] operator
   columnSeriesObj = df[column]
   print('Colunm Name : ', column)
   print('Column Contents : ', columnSeriesObj.values)</pre>
<p><strong>Output:</strong></p>
<pre>Colunm Name : City
Column Contents : ['Sydney' 'Delhi' 'New York' 'Delhi']
Colunm Name : Age
Column Contents : [34 31 16 32]
Colunm Name : Name
Column Contents : ['Abhishek' 'Sumit' 'Sampad' 'Shikha']
</pre>
<p>We have used <code class="EnlighterJSRAW" data-enlighter-language="generic">reversed(df.columns)</code>which given us the reverse column name and its content.</p>
<h3><a id="Iterate_Over_columns_in_dataframe_by_index_using_iloc[]"></a>Iterate Over columns in dataframe by index using iloc[]</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import pandas as pd
employees = [('Abhishek', 34, 'Sydney') ,
             ('Sumit', 31, 'Delhi') ,
             ('Sampad', 16, 'New York') ,
             ('Shikha', 32,'Delhi') , ]
#load data into a DataFrame object:
df = pd.DataFrame(employees, columns=['Name', 'Age', 'City'], index=['a', 'b', 'c', 'd'])
# Yields a tuple of column name and series for each column in the dataframe
for index in range(df.shape[1]):
   print('Column Number : ', index)
   # Select column by index position using iloc[]
   columnSeriesObj = df.iloc[: , index]
   print('Column Contents : ', columnSeriesObj.values)

</pre>
<p><strong>Output:</strong></p>
<pre>Column Number : 0
Column Contents : ['Abhishek' 'Sumit' 'Sampad' 'Shikha']
Column Number : 1
Column Contents : [34 31 16 32]
Column Number : 2
Column Contents : ['Sydney' 'Delhi' 'New York' 'Delhi']

</pre>
<p>So in the above example, you can see that we have iterate over all columns of the dataframe from the 0th index to the last index column. We have selected the contents of the columns using iloc[].</p>
<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</strong></p>
<ul>
<li><a href="https://python-programs.com/pandas-how-to-merge-dataframes-using-dataframe-merge-in-python-part-1/">How to merge Dataframes using Dataframe.merge() in Python?</a></li>
<li><a href="https://python-programs.com/pandas-merge-dataframes-on-specific-columns-or-on-index-in-python-part-2/">How to merge Dataframes on specific columns or on index in Python?</a></li>
<li><a href="https://python-programs.com/pandas-how-to-merge-dataframes-by-index-using-dataframe-merge/">How to merge Dataframes by index using Dataframe.merge()?</a></li>
<li><a href="https://python-programs.com/python-count-nan-and-missing-values-in-dataframe-using-pandas/">Count NaN or missing values in DataFrame</a></li>
<li><a href="https://python-programs.com/pandas-count-rows-in-a-dataframe-all-or-those-only-that-satisfy-a-condition/">Count rows in a dataframe | all or those only that satisfy a condition</a></li>
<li><a href="https://python-programs.com/pandas-6-different-ways-to-iterate-over-rows-in-a-dataframe-update-while-iterating-row-by-row/">6 Different ways to iterate over rows in a Dataframe &amp; Update while iterating row by row</a></li>
<li><a href="https://python-programs.com/python-pandas-how-to-display-full-dataframe-i-e-print-all-rows-columns-without-truncation/">How to display full Dataframe i.e. print all rows &amp; columns without truncation</a></li>
</ul>
<h3>Conclusion:</h3>
<p>At last, I can say that the above-explained different methods to iterate over all or certain columns of a dataframe. aids you a lot in understanding the Pandas: Loop or Iterate over all or certain columns of a dataframe. Thank you!</p>
<p>The post <a href="https://python-programs.com/pandas-loop-or-iterate-over-all-or-certain-columns-of-a-dataframe/">Pandas : Loop or Iterate over all or certain columns of a dataframe</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4953</post-id>	</item>
		<item>
		<title>Sorting 2D Numpy Array by column or row in Python &#124; How to sort the NumPy array by column or row in Python?</title>
		<link>https://python-programs.com/sorting-2d-numpy-array-by-column-or-row-in-python/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Sat, 28 Oct 2023 10:57:36 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=5209</guid>

					<description><![CDATA[<p>In this tutorial, we are going to discuss how to sort the NumPy array by column or row in Python. Just click on the direct links available here and directly jump into the example codes on sorting 2D Numpy Array by Column or Row in Python. How to Sort the NumPy array by Column in [&#8230;]</p>
<p>The post <a href="https://python-programs.com/sorting-2d-numpy-array-by-column-or-row-in-python/">Sorting 2D Numpy Array by column or row in Python | How to sort the NumPy array by column or row in Python?</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this tutorial, we are going to discuss how to sort the NumPy array by column or row in Python. Just click on the direct links available here and directly jump into the example codes on sorting 2D Numpy Array by Column or Row in Python.</p>
<ul>
<li><a href="#How_to_Sort_the_NumPy_array_by_Column_in_Python?">How to Sort the NumPy array by Column in Python?</a>
<ul>
<li><a href="#Sorting_2D_Numpy_Array_by_column_at_index_1">Sorting 2D Numpy Array by column at index 1</a></li>
<li><a href="#Sorting_2D_Numpy_Array_by_column_at_index_0">Sorting 2D Numpy Array by column at index 0</a></li>
<li><a href="#Sorting_2D_Numpy_Array_by_the_Last_Column">Sorting 2D Numpy Array by the Last Column</a></li>
</ul>
</li>
<li><a href="#How_to_Sort_the_NumPy_array_by_Row_in_Python?">How to Sort the NumPy array by Row in Python?</a>
<ul>
<li><a href="#Sorting_2D_Numpy_Array_by_row_at_index_position_1">Sorting 2D Numpy Array by row at index position 1</a></li>
<li><a href="#Sorting_2D_Numpy_Array_by_the_Last_Row">Sorting 2D Numpy Array by the Last Row</a></li>
</ul>
</li>
</ul>
<h2><a id="How_to_Sort_the_NumPy_array_by_Column_in_Python?"></a>How to Sort the NumPy Array by Column in Python?</h2>
<p>In this section, you will be learning the concept of Sorting 2D Numpy Array by a column</p>
<p>Firstly, we have to import a numpy module ie.,</p>
<p><code class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np</code></p>
<p>After that, create a 2D Numpy array i.e.,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)</pre>
<p><strong>Output:</strong></p>
<pre>2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]
</pre>
<p>Suppose if we want to sort this 2D array by 2nd column like this,</p>
<pre>[[21 7 23 14]
[31 10 33 7]
[11 12 13 22]]</pre>
<p>To do that, first, we have to change the positioning of all rows in the 2D numpy array on the basis of sorted values of the 2nd column i.e. column at index 1.</p>
<p><span style="color: #ff6600;">Do Check:</span></p>
<ul>
<li><a href="https://python-programs.com/how-to-sort-a-numpy-array-in-python/">How to sort a Numpy Array in Python?</a></li>
<li><a href="https://python-programs.com/python-convert-matrix-2d-numpy-array-to-a-1d-numpy-array/">Python: Convert Matrix / 2D Numpy Array to a 1D Numpy Array</a></li>
</ul>
<p>Let’s see how to sort it,</p>
<h3><a id="Sorting_2D_Numpy_Array_by_column_at_index_1"></a>Sorting 2D Numpy Array by column at index 1</h3>
<p>In this, we will use <code class="EnlighterJSRAW" data-enlighter-language="generic">arr2D[:,columnIndex].argsort()</code>which will give the array of indices that sort this column.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)
columnIndex = 1
# Sort 2D numpy array by 2nd Column
sortedArr = arr2D[arr2D[:,columnIndex].argsort()]
print('Sorted 2D Numpy Array')
print(sortedArr)</pre>
<p><strong>Output:</strong></p>
<pre>2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Sorted 2D Numpy Array
[[13 10 33 19]
[21 17 13 14]
[21 22 23 20]]

</pre>
<p>So in the above example, you have seen we changed the position of all rows in an array on sorted values of the 2nd column means column at index 1.</p>
<h3><a id="Sorting_2D_Numpy_Array_by_column_at_index_0"></a>Sorting 2D Numpy Array by column at index 0</h3>
<p>Let&#8217;s see how it will work when we give index 0.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)
# Sort 2D numpy array by first column
sortedArr = arr2D[arr2D[:,0].argsort()]
print('Sorted 2D Numpy Array')
print(sortedArr)
</pre>
<p><strong>Output:</strong></p>
<pre>2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Sorted 2D Numpy Array
[[13 10 33 19]
[21 22 23 20]
[21 17 13 14]]
</pre>
<h3><a id="Sorting_2D_Numpy_Array_by_the_Last_Column"></a>Sorting 2D Numpy Array by the Last Column</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)
# Sort 2D numpy array by last column
sortedArr = arr2D[arr2D[:, -1].argsort()]
print('Sorted 2D Numpy Array')
print(sortedArr)</pre>
<p><strong>Output:</strong></p>
<pre>2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Sorted 2D Numpy Array
[[21 17 13 14]
[13 10 33 19]
[21 22 23 20]]
</pre>
<h2><a id="How_to_Sort_the_NumPy_array_by_Row_in_Python?"></a>How to Sort the NumPy array by Row in Python?</h2>
<p>By using similar logic, we can also sort a 2D Numpy array by a single row i.e. mix-up the columns of the 2D numpy array to get the furnished row sorted.</p>
<p>Look at the below examples and learn how it works easily,</p>
<p>Let&#8217;s assume, we have a 2D Numpy array i.e.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># Create a 2D Numpy array list of list
arr2D = np.array([[11, 12, 13, 22], [21, 7, 23, 14], [31, 10, 33, 7]])
print('2D Numpy Array')
print(arr2D)</pre>
<p><strong>Output:</strong></p>
<pre>2D Numpy Array
[[11 12 13 22]
[21 7 23 14]
[31 10 33 7]]</pre>
<h3><a id="Sorting_2D_Numpy_Array_by_row_at_index_position_1"></a>Sorting 2D Numpy Array by row at index position 1</h3>
<p>So we are going to use the above example to show how we sort an array by row.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)
# Sort 2D numpy array by 2nd row
sortedArr = arr2D [ :, arr2D[1].argsort()]
print('Sorted 2D Numpy Array')
print(sortedArr)
</pre>
<p><strong>Output:</strong></p>
<pre>2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Sorted 2D Numpy Array
[[23 20 22 21]
[13 14 17 21]
[33 19 10 13]]

</pre>
<p>So you can see that it changed column value, as we selected row at given index position using [] operator and using <code>argsort()</code>we got sorted indices after that we have changed the position of the column to sort our row.</p>
<h3><a id="Sorting_2D_Numpy_Array_by_the_Last_Row"></a>Sorting 2D Numpy Array by the Last Row</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)
# Sort 2D numpy array by last row
sortedArr = arr2D[:, arr2D[-1].argsort()]
print('Sorted 2D Numpy Array')
print(sortedArr)</pre>
<p><strong>Output:</strong></p>
<pre>2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Sorted 2D Numpy Array
[[22 21 20 23]
[17 21 14 13]
[10 13 19 33]]
</pre>
<h3>Conclusion:</h3>
<p>So in this article, I have shown you different ways to sorting 2D Numpy Array by column or row in Python.</p>
<p>Happy learning guys!</p>
<p>The post <a href="https://python-programs.com/sorting-2d-numpy-array-by-column-or-row-in-python/">Sorting 2D Numpy Array by column or row in Python | How to sort the NumPy array by column or row 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">5209</post-id>	</item>
		<item>
		<title>Count occurrences of a value in NumPy array in Python &#124; numpy.count() in Python</title>
		<link>https://python-programs.com/count-occurrences-of-a-value-in-numpy-array-in-python/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Sat, 28 Oct 2023 09:46:25 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=4835</guid>

					<description><![CDATA[<p>Count Occurences of a Value in Numpy Array in Python: In this article, we have seen different methods to count the number of occurrences of a value in a NumPy array in Python. Check out the below given direct links and gain the information about Count occurrences of a value in a NumPy array in [&#8230;]</p>
<p>The post <a href="https://python-programs.com/count-occurrences-of-a-value-in-numpy-array-in-python/">Count occurrences of a value in NumPy array in Python | numpy.count() in Python</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>Count Occurences of a Value in Numpy Array in Python:</strong> In this article, we have seen different methods to count the number of occurrences of a value in a NumPy array in Python. Check out the below given direct links and gain the information about Count occurrences of a value in a NumPy array in Python.</p>
<ul>
<li><a href="#numpy.count()_Function_in_Python">numpy.count() Function in Python</a></li>
<li><a href="#Example_Code_for_Python_numpy.count()_Function">Example Code for Python numpy.count() Function</a></li>
<li><a href="#How_to_count_the_occurrences_of_a_value_in_a_NumPy_array_in_Python?">How to count the occurrences of a value in a NumPy array in Python?</a></li>
<li><a href="#Use_count_nonzero()">Use count_nonzero()</a></li>
<li><a href="#Use_sum()">Use sum()</a></li>
<li><a href="#Use_bincount()">Use bincount()</a></li>
<li><a href="#Convert_numpy_array_to_list_and_count_occurrences_of_a_value_in_an_array">Convert numpy array to list and count occurrences of a value in an array</a></li>
<li><a href="#Select_elements_from_the_array_that_matches_the_value_and_count_them">Select elements from the array that matches the value and count them</a></li>
<li><a href="#Count_occurrences_of_a_value_in_2D_NumPy_Array">Count occurrences of a value in 2D NumPy Array</a></li>
<li><a href="#Count_occurrences_of_a_value_in_each_row_of_2D_NumPy_Array">Count occurrences of a value in each row of 2D NumPy Array</a></li>
<li><a href="#Count_occurrences_of_a_value_in_each_column_of_2D_NumPy_Array">Count occurrences of a value in each column of 2D NumPy Array</a></li>
</ul>
<h2><a id="numpy.count()_Function_in_Python"></a>Python numpy.count() Function</h2>
<p>The function of <code>numpy.count()</code>in python aid in the counts for the non-overlapping occurrence of sub-string in the specified range. The syntax for phyton numpy.count() function is as follows:</p>
<h3>Syntax:</h3>
<p><code class="EnlighterJSRAW" data-enlighter-language="python">numpy.core.defchararray.count(arr, substring, start=0, end=None)</code></p>
<h3>Parameters:</h3>
<ul>
<li><em><strong>arr:</strong></em> array-like or string to be searched.</li>
<li><em><strong>substring:</strong></em> substring to search for.</li>
<li><em><strong>start, end:</strong> </em>[int, optional] Range to search in.</li>
</ul>
<h3>Returns:</h3>
<p>An integer array with the number of non-overlapping occurrences of the substring.</p>
<h2><a id="Example_Code_for_Python_numpy.count()_Function"></a>Example Code for numpy.count() Function in Python</h2>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-17759" src="https://python-programs.com/wp-content/uploads/2021/05/numpy.count-function-in-python-300x180.png" alt="numpy.count() function in python" width="640" height="384" srcset="https://python-programs.com/wp-content/uploads/2021/05/numpy.count-function-in-python-300x180.png 300w, https://python-programs.com/wp-content/uploads/2021/05/numpy.count-function-in-python-768x460.png 768w, https://python-programs.com/wp-content/uploads/2021/05/numpy.count-function-in-python.png 791w" sizes="(max-width: 640px) 100vw, 640px" /></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># Python Program illustrating 
# numpy.char.count() method 
import numpy as np 
  
# 2D array 
arr = ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']
  
print ("arr : ", arr)
  
print ("Count of 'Aa'", np.char.count(arr, 'Aa'))
print ("Count of 'Aa'", np.char.count(arr, 'Aa', start = 8))</pre>
<p><strong>Output:</strong></p>
<pre>arr : ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']

Count of 'Aa' [1 1 1 1]
Count of 'Aa' [1 0 0 0]</pre>
<p><span style="color: #ff6600;">Also Check:</span></p>
<ul>
<li><a href="https://python-programs.com/how-to-sort-a-numpy-array-in-python/">How to sort a Numpy Array in Python?</a></li>
<li><a href="https://python-programs.com/numpy-amin-find-minimum-value-in-numpy-array-and-its-index/">numpy.amin() | Find minimum value in Numpy Array and it’s index</a></li>
</ul>
<h2><a id="How_to_count_the_occurrences_of_a_value_in_a_NumPy_array_in_Python?"></a>How to count the occurrences of a value in a NumPy array in Python</h2>
<p>Counting the occurrences of a value in a NumPy array means returns the frequency of the value in the array. Here are the various methods used to count the occurrences of a value in a python numpy array.</p>
<h3><a id="Use_count_nonzero()"></a>Use count_nonzero()</h3>
<p>We use the <code>count_nonzero()</code>function to count occurrences of a value in a NumPy array, which returns the count of values in a given numpy array. If the value of the axis argument is None, then it returns the count.</p>
<p>Let&#8217;s take an example, count all occurrences of value ‘6’ in an array,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
print('Numpy Array:')
print(arr)
# Count occurrence of element '3' in numpy array
count = np.count_nonzero(arr == 6)
print('Total occurences of "6" in array: ', count)</pre>
<p><strong>Output:</strong></p>
<pre>RESTART: C:/Users/HP/Desktop/article3.py
Numpy Array:
[9 6 7 5 6 4 5 6 5 4 7 8 6 6 7]
Total occurences of "6" in array: 5

</pre>
<p>In the above example, you have seen that we applied a condition to the numpy array ie., arr==6, then it applies the condition on each element of the array and stores the result as a bool value in a new array.</p>
<h3><a id="Use_sum()"></a>Use sum()</h3>
<p>In this, we are using the<code>sum()</code>function to count occurrences of a value in an array.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
print('Numpy Array:')
print(arr)
# Count occurrence of element '6' in numpy array
count = (arr == 6).sum()

print('Total occurences of "6" in array: ', count)</pre>
<p><strong>Output:</strong></p>
<pre>RESTART: C:/Users/HP/Desktop/article3.py
Numpy Array: [9 6 7 5 6 4 5 6 5 4 7 8 6 6 7]
Total occurences of "6" in array: 5
</pre>
<p>In the above example, we have seen if the given condition is true then it is equivalent to one in python so we can add the True values in the array to get the sum of values in the array.</p>
<h3><a id="Use_bincount()"></a>Use bincount()</h3>
<p>We use<code>bincount()</code>function to count occurrences of a value in an array.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
count_arr = np.bincount(arr)
# Count occurrence of element '6' in numpy array
print('Total occurences of "6" in array: ', count_arr[6])
# Count occurrence of element '5' in numpy array
print('Total occurences of "5" in array: ', count_arr[5])</pre>
<p><strong>Output:</strong></p>
<pre>RESTART: C:/Users/HP/Desktop/article3.py
Total occurences of "6" in array: 5
Total occurences of "5" in array: 3
</pre>
<h3><a id="Convert_numpy_array_to_list_and_count_occurrences_of_a_value_in_an_array"></a>Convert numpy array to list and count occurrences of a value in an array</h3>
<p>In this method, first we convert the array to a list and then we apply<code>count()</code>function on the list to get the count of occurrences of an element.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
# Count occurrence of element '6' in numpy array
count = arr.tolist().count(6)
print('Total occurences of "6" in array: ', count)</pre>
<p><strong>Output:</strong></p>
<pre>RESTART: C:/Users/HP/Desktop/article3.py
Total occurences of "6" in array:</pre>
<h3><a id="Select_elements_from_the_array_that_matches_the_value_and_count_them"></a>Select elements from the array that matches the value and count them</h3>
<p>We can choose only those elements from the numpy array that is similar to a presented value and then we can attain the length of this new array. It will furnish the count of occurrences of the value in the original array. For instance,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [5, 3, 5],
                    [4, 7, 8],
                    [3, 6, 2]] )
# Count occurrence of element '3' in each column
count = np.count_nonzero(matrix == 3, axis=0)
print('Total occurrences  of "3" in each column of 2D array: ', count)</pre>
<p><strong>Output: </strong></p>
<pre>Total occurrences of "3" in each column of 2D array: [1 3 0]</pre>
<h3><a id="Count_occurrences_of_a_value_in_2D_NumPy_Array"></a>Count occurrences of a value in 2D NumPy Array</h3>
<p>We can use the count_nonzero() function to count the occurrences of a value in a 2D array or matrix.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [5, 6, 5],
                    [6, 7, 6],
                    [3, 6, 2]] )
# Count occurrence of element '6' in complete 2D Numpy Array
count = np.count_nonzero(matrix == 6)
print('Total occurrences of "6" in 2D array:')
print(count)
</pre>
<p><strong>Output:</strong></p>
<pre>Total occurrences of "6" in 2D array: 4</pre>
<h3><a id="Count_occurrences_of_a_value_in_each_row_of_2D_NumPy_Array"></a>Count occurrences of a value in each row of 2D NumPy Array</h3>
<p>To count the occurrences of a value in each row of the 2D  array we will pass the axis value as 1 in the count_nonzero() function.</p>
<p>It will return an array containing the count of occurrences of a value in each row.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [6, 6, 5],
                    [4, 7, 6],
                    [3, 6, 2]] )
# Count occurrence of element '6' in each row
count = np.count_nonzero(matrix == 6, axis=1)
print('Total occurrences  of "6" in each row of 2D array: ', count)

</pre>
<p><strong>Output:</strong></p>
<pre>Total occurrences of "6" in each row of 2D array: [0 0 2 1 1]
</pre>
<h3><a id="Count_occurrences_of_a_value_in_each_column_of_2D_NumPy_Array"></a>Count occurrences of a value in each column of 2D NumPy Array</h3>
<p>In order to count the occurrences of a value in each column of the 2D NumPy array transfer the axis value as 0 in the<code>count_nonzero()</code>function. After that, it will result in an array including the count of occurrences of a value in each column. For instance,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [5, 3, 5],
                    [4, 7, 8],
                    [3, 6, 2]] )
# Count occurrence of element '3' in each column
count = np.count_nonzero(matrix == 3, axis=0)
print('Total occurrences  of "3" in each column of 2D array: ', count)</pre>
<p><strong>Output:</strong></p>
<pre>Total occurrences of "3" in each column of 2D array: [1 3 0]</pre>
<p>The post <a href="https://python-programs.com/count-occurrences-of-a-value-in-numpy-array-in-python/">Count occurrences of a value in NumPy array in Python | numpy.count() 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">4835</post-id>	</item>
		<item>
		<title>How to sort a Numpy Array in Python? &#124; numpy.sort() in Python &#124; Python numpy.ndarray.sort() Function</title>
		<link>https://python-programs.com/how-to-sort-a-numpy-array-in-python/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Sat, 28 Oct 2023 09:18:10 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=4740</guid>

					<description><![CDATA[<p>In this article, we are going to show you sorting a NumpyArray in descending and in ascending order or sorts the elements from largest to smallest value or smallest to largest value. Stay tuned to this page and collect plenty of information about the numpy.sort() in Python and How to sort a Numpy Array in [&#8230;]</p>
<p>The post <a href="https://python-programs.com/how-to-sort-a-numpy-array-in-python/">How to sort a Numpy Array in Python? | numpy.sort() in Python | Python numpy.ndarray.sort() Function</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this article, we are going to show you sorting a NumpyArray in descending and in ascending order or sorts the elements from largest to smallest value or smallest to largest value. Stay tuned to this page and collect plenty of information about the numpy.sort() in Python and How to sort a Numpy Array in Python?</p>
<ul>
<li><a href="#Sorting_Arrays">Sorting Arrays</a></li>
<li><a href="#numpy.ndarray.sort()_in_Python">numpy.ndarray.sort() in Python</a></li>
<li><a href="#Python_numpy.sort()_method">Python numpy.sort() method</a></li>
<li><a href="#Sort_a_Numpy_Array_in_Place">Sort a Numpy Array in Place</a></li>
<li><a href="#Sort_a_Numpy_array_in_Descending_Order">Sort a Numpy array in Descending Order</a></li>
<li><a href="#Sorting_a_numpy_array_with_different_kinds_of_sorting_algorithms">Sorting a numpy array with different kinds of sorting algorithms</a></li>
<li><a href="#Sorting_a_2D_numpy_array_along_with_the_axis">Sorting a 2D numpy array along with the axis</a></li>
</ul>
<h2><a id="Sorting_Arrays"></a>Sorting Arrays</h2>
<p>Giving arrays to an ordered sequence is called sorting. An ordered sequence can be any sequence like numeric or alphabetical, ascending or descending.</p>
<p>Python’s Numpy module provides two different methods to sort a numpy array.</p>
<h2><a id="numpy.ndarray.sort()_in_Python"></a>numpy.ndarray.sort() method in Python</h2>
<p>A member function of the ndarray class is as follows:</p>
<p><code class="EnlighterJSRAW" data-enlighter-language="python">ndarray.sort(axis=-1, kind='quicksort', order=None)</code></p>
<p>This can be ordered through a numpy array object (ndarray) and it classifies the incorporated numpy array in place.</p>
<p><span style="color: #ff6600;">Do Check:</span></p>
<ul>
<li><a href="https://python-programs.com/numpy-amin-find-minimum-value-in-numpy-array-and-its-index/">numpy.amin() | Find minimum value in Numpy Array and it’s index</a></li>
<li><a href="https://python-programs.com/python-convert-matrix-2d-numpy-array-to-a-1d-numpy-array/">Python: Convert Matrix / 2D Numpy Array to a 1D Numpy Array</a></li>
</ul>
<h2><a id="Python_numpy.sort()_method"></a>Python numpy.sort() method</h2>
<p>One more method is a global function in the numpy module i.e.</p>
<p><code class="EnlighterJSRAW" data-enlighter-language="python">numpy.sort(array, axis=-1, kind='quicksort', order=None)</code></p>
<p>It allows a numpy array as an argument and results in a sorted copy of the Numpy array.</p>
<p>Where,</p>
<table border="1">
<tbody>
<tr>
<th>Sr.No.</th>
<th>Parameter &amp; Description</th>
</tr>
<tr>
<td>1</td>
<td><b>a</b></p>
<p>Array to be sorted</td>
</tr>
<tr>
<td>2</td>
<td><b>axis</b></p>
<p>The axis along which the array is to be sorted. If none, the array is flattened, sorting on the last axis</td>
</tr>
<tr>
<td>3</td>
<td><b>kind</b></p>
<p>Default is quicksort</td>
</tr>
<tr>
<td>4</td>
<td><b>order</b></p>
<p>If the array contains fields, the order of fields to be sorted</td>
</tr>
</tbody>
</table>
<h3><a id="Sort_a_Numpy_Array_in_Place"></a>Sort a Numpy Array in Place</h3>
<p>The NumPy ndarray object has a function called sort() that we will use for sorting.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a Numpy array from list of numbers
arr = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
array = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
# Sort the numpy array inplace
array.sort()
print('Original Array : ', arr)
print('Sorted Array : ', array)
</pre>
<p><strong>Output:</strong></p>
<pre>RESTART: C:/Users/HP/Desktop/article3.py
Original Array : [ 9 1 3 2 17 5 2 8 14]
Sorted Array : [ 1 2 2 3 5 8 9 14 17]

</pre>
<p>So in the above example, you have seen that using<code>array.sort()</code>we have sorted our array in place.</p>
<h3><a id="Sort_a_Numpy_array_in_Descending_Order"></a>Sort a Numpy array in Descending Order</h3>
<p>In the above method, we have seen that by default both numpy.sort() and ndarray.sort() sorts the numpy array in ascending order. But now, you will observe how to sort an array in descending order?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np
# Create a Numpy array from list of numbers
arr = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
array = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
# Sort the numpy array inplace
array = np.sort(arr)[::-1]

# Get a sorted copy of numpy array (Descending Order)
print('Original Array : ', arr)
print('Sorted Array : ', array)
</pre>
<p><strong>Output:</strong></p>
<pre>RESTART: C:/Users/HP/Desktop/article3.py
Original Array : [ 9 1 3 2 17 5 2 8 14]
Sorted Array : [17 14 9 8 5 3 2 2 1]
</pre>
<h3><a id="Sorting_a_numpy_array_with_different_kinds_of_sorting_algorithms"></a>Sorting a numpy array with different kinds of sorting algorithms</h3>
<p>While sorting sort() function accepts a parameter &#8216;kind&#8217; that tells about the sorting algorithm to be used. If not provided then the default value is <strong>‘</strong>quicksort<strong>’</strong>. To sort numpy array with another sorting algorithm pass this ‘kind’ argument.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np
# Create a Numpy array from list of numbers
arr = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
array = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
# Sort the numpy array using different algorithms

#Sort Using 'mergesort'
sortedArr1 = np.sort(arr, kind='mergesort')

# Sort Using 'heapsort'
sortedArr2 = np.sort(arr, kind='heapsort')

# Sort Using 'heapsort'
sortedArr3 = np.sort(arr, kind='stable')

# Get a sorted copy of numpy array (Descending Order)
print('Original Array : ', arr)

print('Sorted Array using mergesort: ', sortedArr1)

print('Sorted Array using heapsort : ', sortedArr2)

print('Sorted Array using stable : ', sortedArr3)</pre>
<p><strong>Output:</strong></p>
<pre>RESTART: C:/Users/HP/Desktop/article3.py
Original Array : [ 9 1 3 2 17 5 2 8 14]
Sorted Array using mergesort: [ 1 2 2 3 5 8 9 14 17]
Sorted Array using heapsort : [ 1 2 2 3 5 8 9 14 17]
Sorted Array using stable : [ 1 2 2 3 5 8 9 14 17]</pre>
<h3><a id="Sorting_a_2D_numpy_array_along_with_the_axis"></a>Sorting a 2D numpy array along with the axis</h3>
<p>numpy.sort() and numpy.ndarray.sort() provides an argument axis to sort the elements along the axis.<br />
Let’s create a 2D Numpy Array.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a 2D Numpy array list of list

arr2D = np.array([[8, 7, 1, 2], [3, 2, 3, 1], [29, 32, 11, 9]])

print(arr2D)
</pre>
<p><strong>Output:</strong></p>
<pre>RESTART: C:/Users/HP/Desktop/article3.py
[[ 8 7 1 2]
[ 3 2 3 1]
[29 32 11 9]]
</pre>
<p>Now sort contents of each column in 2D numpy Array,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a 2D Numpy array list of list

arr2D = np.array([[8, 7, 1, 2], [3, 2, 3, 1], [29, 32, 11, 9]])
arr2D.sort(axis=0)
print('Sorted Array : ')
print(arr2D)
</pre>
<p><strong>Output:</strong></p>
<pre>RESTART: C:/Users/HP/Desktop/article3.py
Sorted Array :
[[ 3 2 1 1]
[ 8 7 3 2]
[29 32 11 9]]
</pre>
<p>So here is our sorted 2D numpy array.</p>
<p>The post <a href="https://python-programs.com/how-to-sort-a-numpy-array-in-python/">How to sort a Numpy Array in Python? | numpy.sort() in Python | Python numpy.ndarray.sort() Function</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4740</post-id>	</item>
		<item>
		<title>Python: Convert Matrix / 2D Numpy Array to a 1D Numpy Array &#124; How to make a 2d Array into a 1d Array in Python?</title>
		<link>https://python-programs.com/python-convert-matrix-2d-numpy-array-to-a-1d-numpy-array/</link>
		
		<dc:creator><![CDATA[Shikha Mishra]]></dc:creator>
		<pubDate>Sat, 28 Oct 2023 07:58:49 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=5671</guid>

					<description><![CDATA[<p>This article is all about converting 2D Numpy Array to a 1D Numpy Array. Changing a 2D NumPy array into a 1D array returns in an array containing the same elements as the original, but with only one row. Want to learn how to convert 2d Array into 1d Array using Python? Then, stay tuned [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-convert-matrix-2d-numpy-array-to-a-1d-numpy-array/">Python: Convert Matrix / 2D Numpy Array to a 1D Numpy Array | How to make a 2d Array into a 1d Array in Python?</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>This article is all about converting 2D Numpy Array to a 1D Numpy Array. Changing a 2D NumPy array into a 1D array returns in an array containing the same elements as the original, but with only one row. Want to learn how to convert 2d Array into 1d Array using Python? Then, stay tuned to this tutorial and jump into the main heads via the available links shown below:</p>
<ul>
<li><a href="#Convert_2D_Numpy_array_/_Matrix_to_a_1D_Numpy_array_using_flatten()">Convert 2D Numpy array / Matrix to a 1D Numpy array using flatten()</a></li>
<li><a href="#Convert_2D_Numpy_array_to_1D_Numpy_array_using_numpy.ravel()">Convert 2D Numpy array to 1D Numpy array using numpy.ravel()</a></li>
<li><a href="#Convert_a_2D_Numpy_array_to_a_1D_array_using_numpy.reshape()">Convert a 2D Numpy array to a 1D array using numpy.reshape()</a></li>
<li><a href="#numpy.reshape()_and_-1_size">numpy.reshape() and -1 size</a></li>
<li><a href="#numpy.reshape()_returns_a_new_view_object_if_possible">numpy.reshape() returns a new view object if possible</a></li>
<li><a href="#Convert_2D_Numpy_array_to_1D_array_but_Column_Wise">Convert 2D Numpy array to 1D array but Column Wise</a></li>
</ul>
<h2><a id="Convert_2D_Numpy_array_/_Matrix_to_a_1D_Numpy_array_using_flatten()"></a>Convert 2D Numpy array / Matrix to a 1D Numpy array using flatten()</h2>
<p>Python Numpy provides a function flatten() to convert an array of any shape to a flat 1D array.</p>
<p>Firstly, it is required to import the numpy module,</p>
<p><code class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np</code></p>
<p>Syntax:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">ndarray.flatten(order='C')
ndarray.flatten(order='F')
ndarray.flatten(order='A')</pre>
<p>Order: In which items from the array will be read</p>
<p>Order=&#8217;C&#8217;: It will read items from array row-wise</p>
<p>Order=&#8217;F&#8217;: It will read items from array row-wise</p>
<p>Order=&#8217;A&#8217;: It will read items from array-based on memory order</p>
<p>Suppose we have a 2D Numpy array or matrix,</p>
<p>[7 4 2]<br />
[5 3 6]<br />
[2 9 5]</p>
<p>Which we have to convert in a 1D array. Let&#8217;s use this to convert a 2D numpy array or matrix to a new flat 1D numpy array,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# get a flatten 1D copy of 2D Numpy array
flat_array = arr.flatten()
print('1D Numpy Array:')
print(flat_array)</pre>
<p><strong>Output:</strong></p>
<pre>1D Numpy Array:
[7 4 2 5 3 6 2 9 5]
</pre>
<p>If we made any changes in our 1D array it will not affect our original 2D array.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# get a flatten 1D copy of 2D Numpy array
flat_array = arr.flatten()
print('1D Numpy Array:')
print(flat_array)
# Modify the flat 1D array
flat_array[0] = 50
print('Modified Flat Array: ')
print(flat_array)
print('Original Input Array: ')
print(arr)</pre>
<p><strong>Output:</strong></p>
<pre>1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

Modified Flat Array:
[50 4 2 5 3 6 2 9 5]

Original Input Array:
[[7 4 2]
[5 3 6]
[2 9 5]]
</pre>
<p>Also Check:</p>
<ul>
<li><a href="https://python-programs.com/pandas-count-rows-in-a-dataframe-all-or-those-only-that-satisfy-a-condition/">Pandas: count rows in a dataframe | all or those only that satisfy a condition</a></li>
<li><a href="https://python-programs.com/python-numpy-select-rows-columns-by-index-from-a-2d-numpy-array-multi-dimension/">Python Numpy: Select rows/columns by index from a 2D Numpy Array | Multi Dimension</a></li>
</ul>
<h2><a id="Convert_2D_Numpy_array_to_1D_Numpy_array_using_numpy.ravel()"></a>Convert 2D Numpy array to 1D Numpy array using numpy.ravel()</h2>
<p>Numpy have  a built-in function &#8216;numpy.ravel()&#8217; that accepts an array element as parameter and returns a flatten 1D array.</p>
<p><strong>Syntax:</strong></p>
<p><code class="EnlighterJSRAW" data-enlighter-language="generic">numpy.ravel(input_arr, order='C')</code></p>
<p>Let&#8217;s make use of this syntax to convert 2D array to 1D array,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Get a flattened view of 2D Numpy array
flat_array = np.ravel(arr)
print('Flattened 1D Numpy array:')
print(flat_array)
</pre>
<p><strong>Output:</strong></p>
<pre>Flattened 1D Numpy array:
[7 4 2 5 3 6 2 9 5]

</pre>
<p>If we made any changes in our 1D array using numpy.ravel() it will also affect our original 2D array.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Get a flattened view of 2D Numpy array
flat_array = np.ravel(arr)
print('Flattened 1D Numpy array:')
print(flat_array)
# Modify the 2nd element  in flat array
flat_array[1] = 12
# Changes will be reflected in both flat array and original 2D array
print('Modified Flattened 1D Numpy array:')
print(flat_array)
print('2D Numpy Array:')
print(arr)
</pre>
<p><strong>Output:</strong></p>
<pre>Flattened 1D Numpy array:
[7 4 2 5 3 6 2 9 5]
Modified Flattened 1D Numpy array:
[ 7 12 2 5 3 6 2 9 5]
2D Numpy Array:
[[ 7 12 2]
[ 5 3 6]
[ 2 9 5]]

</pre>
<h2><a id="Convert_a_2D_Numpy_array_to_a_1D_array_using_numpy.reshape()"></a>Convert a 2D Numpy array to a 1D array using numpy.reshape()</h2>
<p>Numpy provides a built-in function reshape() to convert the shape of a numpy array,</p>
<p>It accepts three arguments-</p>
<ul>
<li>a: Array which we have to be reshaped</li>
<li>newshape: Newshape can be a tuple or integer</li>
<li>order: The order in which items from the input array will be used</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])

# convert 2D array to a 1D array of size 9
flat_arr = np.reshape(arr, 9)
print('1D Numpy Array:')
print(flat_arr)
</pre>
<p><strong>Output:</strong></p>
<pre>1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

</pre>
<p>In the above example, we have pass 9 as an argument because there were a total of 9 elements (3X3) in the 2D input array.</p>
<h3><a id="numpy.reshape()_and_-1_size"></a>numpy.reshape() and -1 size</h3>
<p>This function can be used when the input array is too big and multidimensional or we just don’t know the total elements in the array. In such scenarios, we can pass the size as -1.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])

# convert 2D array to a 1D array without mentioning the actual size
flat_arr = np.reshape(arr, -1)
print('1D Numpy Array:')
print(flat_arr)</pre>
<p><strong>Output:</strong></p>
<pre>1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

</pre>
<h3><a id="numpy.reshape()_returns_a_new_view_object_if_possible"></a>numpy.reshape() returns a new view object if possible</h3>
<p>With the help of reshape() function, we can view the input array and any modification done in the view object will be reflected in the original input too.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
[5, 3, 6],
[2, 9, 5]])
flat_arr = np.reshape(arr,-1)
print('1D Numpy Array:')
print(flat_arr)
# Modify the element at the first row and first column in the 1D array
arr[0][0] = 11
print('1D Numpy Array:')
print(flat_arr)
print('2D Numpy Array:')
print(arr)</pre>
<p><strong>Output:</strong></p>
<pre>1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

1D Numpy Array:
[11 4 2 5 3 6 2 9 5]

2D Numpy Array:

[[11 4 2]
[ 5 3 6]
[ 2 9 5]]

</pre>
<h3><a id="Convert_2D_Numpy_array_to_1D_array_but_Column_Wise"></a>Convert 2D Numpy array to 1D array but Column Wise</h3>
<p>If we pass the order parameter in reshape() function as “F” then it will read 2D input array column-wise. As we will show below-</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Read 2D array column by column and create 1D array from it
flat_arr = np.reshape(arr, -1, order='F')
print('1D Numpy Array:')
print(flat_arr)
</pre>
<p><strong>Output:</strong></p>
<pre>1D Numpy Array:
[7 5 2 4 3 9 2 6 5]
</pre>
<p>The post <a href="https://python-programs.com/python-convert-matrix-2d-numpy-array-to-a-1d-numpy-array/">Python: Convert Matrix / 2D Numpy Array to a 1D Numpy Array | How to make a 2d Array into a 1d Array in Python?</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5671</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-06-21 08:56:26 by W3 Total Cache
-->