How to get the column name when iterating through dataframe pandas?

When iterating over a dataframe using df.iterrows:

for i, row in df.iterrows():
    ...

Each row row is converted to a Series, where row.index corresponds to df.columns, and row.values corresponds to df.loc[i].values, the column values at row i.


Minimal Code Sample

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}, index=['a', 'b'])
df
   A  B
a  1  3
b  2  4

row = None
for i, row in df.iterrows():
     print(row['A'], row['B'])         
# 1 3
# 2 4

row   # outside the loop, `row` holds the last row    
A    2
B    4
Name: b, dtype: int64

row.index
# Index(['A', 'B'], dtype='object')

row.index.equals(df.columns)
# True

row.index[0]
# A

You are already getting to column name, so if you just want to drop the series you can just use the throwaway _ variable when starting the loop.

for column_name, _ in df.iteritems():
    # do something

However, I don't really understand the use case. You could just iterate over the column names directly:

for column in df.columns:
    # do something

Tags:

Python

Pandas