Python Pandas DataFrame items() Function

Pandas DataFrame items() Function:

The items() function of the pandas dataframe iterates over the (column name, Series) pairs.

Iterate over the DataFrame columns with the items() method of the Pandas DataFrame, which returns a tuple containing the column name and the content as a Series.

Syntax:

DataFrame.items()

Parameters: This method doesn’t accept any parameters

Return Value:

Gives the following:

label: This is required. The type of this is an object. The names of the columns in the DataFrame being iterated over.

content: This is required. The type of this is a series. The column entries belonging to each label, as a Series.

Pandas DataFrame items() Function in Python

Approach:

  • Import pandas module using the import keyword.
  • Import NumPy module using the import keyword.
  • Pass some random key-value pair(dictionary), index list as arguments to the DataFrame() function of the pandas module to create a dataframe
  • Print the given dataframe
  • Loop in the label and data of the dataframe using the for loop and the items() functions and print the corresponding label and data.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Import NumPy module using the import keyword.
import numpy as np
# Pass some random key-value pair(dictionary), index list as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
data_frme = pd.DataFrame({
  "emp_name": ["john", "nick" , "jessy", "mary"],
  "emp_age": [25, 35, 38, 22],
  "emp_salary": [25000, 40000, 22000, 80000]},
  index= [1, 2, 3, 4]
)
# Print the  given dataframe
print("The given Dataframe:")
print(data_frme)
print()
# Loop in the label and data of the dataframe using the for loop and the items() functions
# and print the corresponding label and data
for label, data in data_frme.items():
  print(f'label: {label}')
  print(f'data: \n{data}')
  print()

Output:

The given Dataframe:
  emp_name  emp_age  emp_salary
1     john       25       25000
2     nick       35       40000
3    jessy       38       22000
4     mary       22       80000

label: emp_name
data: 
1     john
2     nick
3    jessy
4     mary
Name: emp_name, dtype: object

label: emp_age
data: 
1    25
2    35
3    38
4    22
Name: emp_age, dtype: int64

label: emp_salary
data: 
1    25000
2    40000
3    22000
4    80000
Name: emp_salary, dtype: int64