Iterate over Columns of DataFrame

To iterate over the DataFrame columns in Pandas, call items() method on this DataFrame. DataFrame.items() iterates over the DataFrame columns, returning a tuple with the column name and content in the column. Content of the column in a pandas Series object.

In this tutorial, we will learn the syntax of DataFrame.items() method and how to use this method to iterate over the columns of this DataFrame.

Syntax

The syntax of DataFrame.items() method is

</>
Copy
DataFrame.items()

This method does not have any parameters.

Examples

Iterate over Columns of DataFrame

In the following program, we take a DataFrame with three columns and iterate over the columns using DataFrame.items() method.

Example.py

</>
Copy
import pandas as pd

data = {'col_1': [10, 20, 30], 'col_2': [40, 50, 60], 'col_3': [70, 80, 90]}
df = pd.DataFrame(data)

for (col_name, content) in df.items():
    print(col_name)
    print(content)

Output

col_1
0    10
1    20
2    30
Name: col_1, dtype: int64
col_2
0    40
1    50
2    60
Name: col_2, dtype: int64
col_3
0    70
1    80
2    90
Name: col_3, dtype: int64

Iterate over Empty Columns of DataFrame

In the following program, we take a DataFrame with three columns but the columns have no data. We iterate over these columns using DataFrame.items() method.

Example.py

</>
Copy
import pandas as pd

data = {'col_1': [], 'col_2': [], 'col_3': []}
df = pd.DataFrame(data)

for (col_name, content) in df.items():
    print(col_name)
    print(content)

Output

col_1
Series([], Name: col_1, dtype: float64)
col_2
Series([], Name: col_2, dtype: float64)
col_3
Series([], Name: col_3, dtype: float64)

Conclusion

In this Pandas Tutorial, we learned how to iterate over the columns of given DataFrame using pandas DataFrame.items() method.