Different ways to iterate over rows in Pandas Dataframe
In this article, we will see how can you iterate over rows in a Pandas data frame using Python. Pandas is a software library used for data analysis and manipulation in Python.
Requirements:
- Pandas
To get started you need to install Pandas if not already present on your system. You can install it using PIP which is a package installer for Python programming language. You can install it on your system by opening Command Prompt if you are using Windows or Terminal if you are using a Linux or Mac operating system and running the following code.
pip install pandas
Code:
import pandas as pd
#example dataframe
df = pd.DataFrame({'population': [59000000, 65000000, 434000,
434000, 434000, 337000, 337000,
11300, 11300],
'GDP': [1937894, 2583560 , 12011, 4520, 12128,
17036, 182, 38, 311],
'alpha-2': ["IT", "FR", "MT", "MV", "BN",
"IS", "NR", "TV", "AI"],
'country': ["Italy", "France", "Malta",
"Maldives", "Brunei", "Iceland",
"Nauru", "Tuvalu", "Anguilla"]})
print('Given Dataframe: \n\n', df)
print('\nIterating over rows: \n')
#Iterating over rows
for i in df.index:
print(df['country'][i], df['GDP'][i])
Output:
Given Dataframe:
population GDP alpha-2 country
0 59000000 1937894 IT Italy
1 65000000 2583560 FR France
2 434000 12011 MT Malta
3 434000 4520 MV Maldives
4 434000 12128 BN Brunei
5 337000 17036 IS Iceland
6 337000 182 NR Nauru
7 11300 38 TV Tuvalu
8 11300 311 AI Anguilla
Iterating over rows:
Italy 1937894
France 2583560
Malta 12011
Maldives 4520
Brunei 12128
Iceland 17036
Nauru 182
Tuvalu 38
Anguilla 311
Leave a Reply