Pandas DataFrame Items Method

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will learn how to use the items() method in the Pandas library to iterate over a DataFrame's columns. This method returns a generator object that contains tuples of column names and their corresponding Series.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import the necessary libraries

First, we need to import the pandas library:

import pandas as pd

Create a DataFrame

Next, let's create a DataFrame with some sample data:

df = pd.DataFrame({
    "Name": ["Navya", "Vindya"],
    "Age": [25, 24],
    "Education": ["M.Tech", "Ph.d"]
}, index=['id001', 'id002'])

Iterate over column names

To iterate over the column names of the DataFrame, we can use the items() method. This method returns a generator object. We can print it or iterate over it using a for loop:

print("Iterating over column names using items():")

for column_name, data in df.items():
    print('Column Name:', column_name)

Iterate over column values

To access the values of each column, we can use the items() method in combination with a for loop. Each iteration will return a tuple of the column name and the corresponding Series:

print("Iterating over column values using items():")

for column_name, data in df.items():
    print('Column Name:', column_name)
    print('Data:', data)

Iterate over a specific row

To iterate over a specific row, we can use the index number and access the row through the Series object:

print("Iterating over a specific row using items():")

for column_name, data in df.items():
    print('Column Name:', column_name)
    print('Data:', data[0])  ## Access the first item of the Series

Iterate over a specific column

To iterate over a specific column, we can use the column name as an index for the data object:

print("Iterating over a specific column using items():")

for column_name, data in df.items():
    print('Column Name:', column_name)
    print('Data:', data['id001'])  ## Access the value at 'id001' index

Summary

In this lab, we learned how to use the items() method in the Pandas library to iterate over a DataFrame's columns. We saw how to iterate over column names, column values, specific rows, and specific columns. The items() method provides a convenient way to explore and manipulate data within a DataFrame.

Other Python Tutorials you may like