{"id":684,"date":"2023-11-29T07:35:32","date_gmt":"2023-11-29T07:35:32","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=684"},"modified":"2023-12-04T08:54:34","modified_gmt":"2023-12-04T08:54:34","slug":"pandas-iterate-over-rows","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/pandas-iterate-over-rows\/","title":{"rendered":"How to Iterate Over Rows in Pandas? (with Examples)"},"content":{"rendered":"\n<p>One of the most common tasks in data analysis is to loop through rows of a Pandas DataFrame to perform various operations, like data manipulation and wrangling. In this article, we will discover different ways to iterate over rows of Pandas DataFrames.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is a DataFrame?<\/strong><\/h2>\n\n\n\n<p><strong>Pandas DataFrames are a two-dimensional array with labeled data structures having different column types. <\/strong>It is a convenient way to work with structured data in Python. DataFrames are a standard and convenient way to store data in a tabular format, with rows to store the information and columns to name the information.<\/p>\n\n\n\n<p>To learn about DataFrames in detail, you can check out how to <a href=\"https:\/\/favtutor.com\/articles\/convert-pandas-series-to-dataframe\/\">Convert Pandas Series to DataFrame<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>3 Ways to Iterate Over Rows in Pandas DataFrame<\/strong><\/h2>\n\n\n\n<p>Looping through rows in a DataFrame allows us to access and manipulate the values of each row individually.  Let us now explore the various methods to iterate over rows of a Pandas DataFrame:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1) Using the iterrows() Function<\/strong><\/h3>\n\n\n\n<p><strong>The pandas library in Python provides itterows() Function, which we can use to iterate over rows of a DataFrame.<\/strong> It returns an iterator that yields the index and a Series object containing the values of each row. By using the iterrows() function, we can get the values of every row using the column names as indices of the DataFrame.<\/p>\n\n\n\n<p>The following Python code shows how to use iterrows() function to iterate over rows in Pandas DataFrame:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">import pandas as pd\n\ndata = {\n    &quot;Name&quot;: [&quot;John&quot;, &quot;Emma&quot;, &quot;Michael&quot;],\n    &quot;Age&quot;: [45, 30, 55],\n    &quot;City&quot;: [&quot;New York&quot;, &quot;London&quot;, &quot;Paris&quot;]\n}\ndf = pd.DataFrame(data)\n\n# Display the original DataFrame\nprint('Original DataFrame:\\n', df)\n\n# Loop through rows using iterrows()\nprint('Iterated Rows:')\nfor index, row in df.iterrows():\n    print(row['Name'], row['Age'], row['City'])<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Original DataFrame:\n       Name  Age      City\n0     John   45  New York\n1     Emma   30    London\n2  Michael   55     Paris\n\nIterated Rows:\nJohn 45 New York\nEmma 30 London\nMichael 55 Paris\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2) Using List Comprehension<\/strong><\/h3>\n\n\n\n<p>List comprehension is a brief and efficient way to iterate over rows in a DataFrame while performing operations on the data. We can just simply use a list comprehension to iterate over the values of a particular row. <strong>This technique is particularly useful when you need to perform calculations or transformations on the data while iterating.<\/strong><\/p>\n\n\n\n<p>Let us see how to do it in Python:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">import pandas as pd\n\ndata = {\n    &quot;Name&quot;: [&quot;John&quot;, &quot;Emma&quot;, &quot;Michael&quot;],\n    &quot;Age&quot;: [45, 30, 55],\n    &quot;City&quot;: [&quot;New York&quot;, &quot;London&quot;, &quot;Paris&quot;]\n}\ndf = pd.DataFrame(data)\n\n# Display the original DataFrame\nprint('Original DataFrame:\\n', df)\n\n# Loop through rows using list comprehension\nprint('Iterated Rows:')\nresult = [row['Name'] for index, row in df.iterrows()]\nprint(result)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Original DataFrame:\n       Name  Age      City\n0     John   45  New York\n1     Emma   30    London\n2  Michael   55     Paris\n\nIterated Rows:\n&#91;'John', 'Emma', 'Michael']\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3) Using the apply() Function<\/strong><\/h3>\n\n\n\n<p>One more way we can iterate over rows of Pandas DataFrame is by using the <a href=\"https:\/\/favtutor.com\/articles\/pandas-dataframe-apply\/\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/articles\/pandas-dataframe-apply\/\">apply() function<\/a>. The apply() function in Pandas is very productive as it can allow us to apply a function to each row or column of a DataFrame. This function can be defined using a lambda function or a custom-defined function.<\/p>\n\n\n\n<p>Let us try an example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">import pandas as pd\n\ndata = {\n    &quot;Name&quot;: [&quot;John&quot;, &quot;Emma&quot;, &quot;Michael&quot;],\n    &quot;Age&quot;: [45, 30, 55],\n    &quot;City&quot;: [&quot;New York&quot;, &quot;London&quot;, &quot;Paris&quot;]\n}\ndf = pd.DataFrame(data)\n\n# Display the original DataFrame\nprint('Original DataFrame:\\n', df)\n\n# Use apply() with a lambda function\ndf['Name'] = df.apply(lambda row: row['Name'].upper(), axis=1)\n\n# Display the new DataFrame. \nprint('Updated DataFrame:\\n',df)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Original DataFrame:\n       Name  Age      City\n0     John   45  New York\n1     Emma   30    London\n2  Michael   55     Paris\n\nUpdated DataFrame:\n       Name  Age      City\n0     JOHN   45  New York\n1     EMMA   30    London\n2  MICHAEL   55     Paris\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we understood the various techniques and methods we can use to iterate over rows of a Pandas data frame. Now that you have a solid understanding of looping through Pandas, you can confidently apply your learnings from this article to your data analysis projects.  If you need help with them, our <a href=\"https:\/\/favtutor.com\/data-science\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/data-science\">Data Science Tutors<\/a> are always available!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understand how to iterate over rows in pandas dataframe using iterrows(), list comprehension, and apply() functions.<\/p>\n","protected":false},"author":10,"featured_media":686,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[35],"tags":[37],"class_list":["post-684","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-science","tag-pandas"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/684","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/10"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=684"}],"version-history":[{"count":5,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/684\/revisions"}],"predecessor-version":[{"id":815,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/684\/revisions\/815"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/686"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=684"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=684"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=684"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}