Loop Through Index of pandas DataFrame in Python (Example)

 

In this tutorial, I’ll explain how to iterate over the row index of a pandas DataFrame in the Python programming language.

The tutorial consists of these content blocks:

Let’s do this.

 

Example Data & Software Libraries

First, we need to import the pandas library:

import pandas as pd                                # Import pandas

In addition, have a look at the following example data:

data = pd.DataFrame({'x1':['a', 'b', 'c', 'd'],    # Create pandas DataFrame
                     'x2':['w', 'x', 'y', 'z']})
print(data)                                        # Print pandas DataFrame

 

table 1 DataFrame loop through index pandas dataframe python

 

As you can see based on Table 1, our example data is a pandas DataFrame containing four rows and two columns. The row indices range from 0 to 3.

 

Example: Iterate Over Row Index of pandas DataFrame

In this example, I’ll show how to loop through the row indices of a pandas DataFrame in Python.

More precisely, we are using a for loop to print a sentence for each row that tells us the current index position and the values in the columns x1 and x2.

Consider the Python code below:

for i, row in data.iterrows():                     # Initialize for loop
    print('Index', i, '- Column x1:', row['x1'], '- Column x2:', row['x2'])
# Index 0 - Column x1: a - Column x2: w
# Index 1 - Column x1: b - Column x2: x
# Index 2 - Column x1: c - Column x2: y
# Index 3 - Column x1: d - Column x2: z

The previous output shows that we have created an output for each iteration over each index position in our pandas DataFrame.

 

Video, Further Resources & Summary

If you need further information on the topics of this article, you may want to have a look at the following video on my YouTube channel. In the video, I show the Python programming code of this article in a live programming session:

 

The YouTube video will be added soon.

 

Furthermore, you may have a look at some of the related articles on my website.

 

To summarize: You have learned in this article how to loop through the index of a pandas DataFrame in the Python programming language. In case you have additional questions, don’t hesitate to tell me about it in the comments.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top