Informatics Practices

How do you iterate over a dataframe? Explain with the help of code snippet.

Python Data Handling

2 Likes

Answer

Iterating over rows in the DataFrame:

The iterrows() method is used to iterate over each row in the DataFrame. In this method, each horizontal subset is in the form of (row-index, series), where the series contains all column values for that row-index.

For example :

import pandas as pd
total_sales = {2015 : {'Qtr1' : 34500, 'Qtr2' : 45000}, 
               2016 : {'Qtr1' : 44500, 'Qtr2' : 65000}}
df = pd.DataFrame(total_sales)
for (row, rowseries) in df.iterrows():
    print("RowIndex :", row)
    print('Containing :')
    print(rowseries)
Output
RowIndex : Qtr1
Containing :
2015    34500
2016    44500
Name: Qtr1, dtype: int64
RowIndex : Qtr2
Containing :
2015    45000
2016    65000
Name: Qtr2, dtype: int64

Iterating over columns in the DataFrame:

The iteritems() method is used to iterate over each column in the DataFrame. In this method, each vertical subset is in the form of (column-index, series), where the series contains all row values for that column-index.

For example :

import pandas as pd
total_sales = {2015 : {'Qtr1' : 34500, 'Qtr2' : 45000}, 
               2016 : {'Qtr1' : 44500, 'Qtr2' : 65000}}
df = pd.DataFrame(total_sales)
for (col, colseries) in df.iteritems():
    print("Column Index :", col)
    print('Containing :')
    print(colseries)
Output
Column Index : 2015
Containing :
Qtr1    34500
Qtr2    45000
Name: 2015, dtype: int64
Column Index : 2016
Containing :
Qtr1    44500
Qtr2    65000
Name: 2016, dtype: int64

Answered By

1 Like


Related Questions