Professional Documents
Culture Documents
Dataframes IV (Iteration)
Dataframes IV (Iteration)
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])