You are on page 1of 3

Iteration on Rows and Columns of a

dataframe
To repeatedly access data (rowwise or colwise) from dataframe, pandas
provides us with 2 functions:
1. iterrows():Pandas has iterrows() function that will help you loop
through each row of a dataframe. Pandas’ iterrows() returns an iterator
containing index of each row and the data in each row as a Series.
import pandas as pd
dict1={'names':['sush','adarsh','ravi','manu','sushma'],
'marks':[34,45,56,67,98],
'class':[9,10,8,10,11]}
df=pd.DataFrame(dict1,index=[100,101,102,103,104])
for row_index,row in df.iterrows():
print (row)
Output:
names sush
marks 34
class 9
Name: 100, dtype: object
names adarsh
marks 45
class 10
Name: 101, dtype: object
names ravi
marks 56
class 8
Name: 102, dtype: object
names manu
marks 67
class 10
Name: 103, dtype: object
names sushma
marks 98
class 11
Name: 104, dtype: object

Note − Do not try to modify any object while iterating. Iterating is meant for reading and the
iterator returns a copy of the original object (a view), thus the changes will not reflect on the
original object.
1) iteritems():The iteritems() function is used to iterator over (column
name, Series) pairs. It Iterates over the DataFrame columns, returning a
tuple with the column name and the content as a Series
import pandas as pd
dict1={'names':['sush','adarsh','ravi','manu','sushma'],
'marks':[34,45,56,67,98],
'class':[9,10,8,10,11]}
df=pd.DataFrame(dict1,index=[100,101,102,103,104])

for label, content in df.iteritems():


print('label:', label)
print('content:', content, sep='\n')
Output:
label: names
content:
100 sush
101 adarsh
102 ravi
103 manu
104 sushma
Name: names, dtype: object
label: marks
content:
100 34
101 45
102 56
103 67
104 98
Name: marks, dtype: int64
label: class
content:
100 9
101 10
102 8
103 10
104 11
Name: class, dtype: int64
Example:
import pandas as pd
dict1={'names':['sush','adarsh','ravi',
'manu','sushma'],
'marks':[34,45,56,67,98],
'class':[9,10,8,10,11]}
df=pd.DataFrame(dict1,index=[100,101,
102,103,104])
for i,r in df.iterrows():
#if i==102:
#if r['names']=='adarsh':
#if r['class']==10:
if i==102 or i==104:
print(i)
print(r)

You might also like