How to Iterate Over Rows and Columns of Pandas DataFrame in Python
Iteration is the process of taking each item of overall items, one after another. Pandas DataFrame consists of rows and columns so, in order to iterate over DataFrame, we have to iterate a DataFramelike a dictionary. In a dictionary, we iterate over the keys of the object in the same way we have to iterate in DataFrame. In this article, I’ll show here how to iterate over Rows and Columns of Pandas DataFrame in Python.
In this article, I am using a sample DataFrame. Click here to see the topics. Here is the sample DataFrame:
id name math_score 0 202301 Minhaj 92 1 202302 Ridhwan 86 2 202303 Tanveer 76 3 202304 Sharodia 89 4 202305 Alve 99 5 202306 Intisar 99
In Pandas DataFrame we can iterate an element in two ways:
- Iterating over rows
- Iterating over columns
Iterating Over Rows :
In order to iterate over rows, we can use three function iteritems(), iterrows(), itertuples() . These three function will help in iteration over rows.
Using iteritems() Method:
In order to iterate over rows, we apply a iterrows() function. This function returns each index value along with a series containing the data in each row.
for
i, j
in
df.iterrows():
print
(i, j)
print
()
Output:
0 id 202301 name Minhaj math_score 92 Name: 0, dtype: object 1 id 202302 name Ridhwan math_score 86 Name: 1, dtype: object 2 id 202303 name Tanveer math_score 76 Name: 2, dtype: object 3 id 202304 name Sharodia math_score 89 Name: 3, dtype: object 4 id 202305 name Alve math_score 99 Name: 4, dtype: object 5 id 202306 name Intisar math_score 99 Name: 5, dtype: object Using iteritems() Method: Now we apply a iteritems() function in order to retrieve an rows of dataframe.
for
key, value
in
df.iteritems():
print
(key, value)
print
()
id 0 202301 1 202302 2 202303 3 202304 4 202305 5 202306 Name: id, dtype: object name 0 Minhaj 1 Ridhwan 2 Tanveer 3 Sharodia 4 Alve 5 Intisar Name: name, dtype: object math_score 0 92 1 86 2 76 3 89 4 99 5 99 Name: math_score, dtype: int64
itertuples()
Methodfor
i
in
df.itertuples():
print
(i)
Pandas(Index=0, id='202301', name='Minhaj', math_score=92) Pandas(Index=1, id='202302', name='Ridhwan', math_score=86) Pandas(Index=2, id='202303', name='Tanveer', math_score=76) Pandas(Index=3, id='202304', name='Sharodia', math_score=89) Pandas(Index=4, id='202305', name='Alve', math_score=99) Pandas(Index=5, id='202306', name='Intisar', math_score=99)
Iterating Over Rows :
for i in columns:
# printing the third element of the column
print (df[i][2])
Output:
202303 Tanveer 76
In this tutorial, I tried to brief how to iterate over Rows and Columns of Pandas DataFrame in Python. Hope you have enjoyed the tutorial. If you want to get updated, like my facebook page https://www.facebook.com/LearningBigDataAnalytics and stay connected.