You can use the following basic syntax to iterate over columns in a pandas DataFrame:
for name, values in df.iteritems():
print(values)
The following examples show how to use this syntax in practice with the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [25, 12, 15, 14, 19], 'assists': [5, 7, 7, 9, 12], 'rebounds': [11, 8, 10, 6, 6]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6
Example 1: Iterate Over All Columns in DataFrame
The following code shows how to iterate over every column in a pandas DataFrame:
for name, values in df.iteritems():
print(values)
0 25
1 12
2 15
3 14
4 19
Name: points, dtype: int64
0 5
1 7
2 7
3 9
4 12
Name: assists, dtype: int64
0 11
1 8
2 10
3 6
4 6
Name: rebounds, dtype: int64
We can also use the following syntax to iterate over every column and print just the column names:
for name, values in df.iteritems():
print(name)
points
assists
rebounds
Example 2: Iterate Over Specific Columns
The following syntax shows how to iterate over specific columns in a pandas DataFrame:
for name, values in df[['points', 'rebounds']].iteritems():
print(values)
0 25
1 12
2 15
3 14
4 19
Name: points, dtype: int64
0 11
1 8
2 10
3 6
4 6
Name: rebounds, dtype: int64
We can also use the following syntax to iterate over a range of specific columns:
for name, values in df.iloc[:, 0:2].iteritems():
print(values)
0 25
1 12
2 15
3 14
4 19
Name: points, dtype: int64
0 5
1 7
2 7
3 9
4 12
Name: assists, dtype: int64
You can find the complete documentation for the iteritems() function here.
Additional Resources
How to Apply a Function to Selected Columns in Pandas
How to Change the Order of Columns in Pandas
How to Drop Columns by Index in Pandas