Iterating through rows in a DataFrame

In [2]:
from pandas import DataFrame

iterrows

Returns a generator that iterates over rows. Each row is returns as a Series.

In [3]:
df = DataFrame({'alpha': [0.11, 0.18, 0.05, -0.01, -0.42],
                'beta':  [16.8, 27.6, -23.4, 4.0, 15.1],
                'cls':   ['a', 'b', 'b', 'a', 'b']})

for i, event in df.iterrows():
    print(i, event['alpha'])
0 0.11
1 0.18
2 0.05
3 -0.01
4 -0.42

itertuples

Returns a generator that iterates over rows. Each row is returned as a namedtuple.

In [4]:
df = DataFrame({'alpha': [0.11, 0.18, 0.05, -0.01, -0.42],
                'beta':  [16.8, 27.6, -23.4, 4.0, 15.1],
                'cls':   ['a', 'b', 'b', 'a', 'b']})

for event in df.itertuples(index=False):
    alpha, beta, cls = event
    print(alpha, beta)
    
for event in df.itertuples(index=False, name='event'):
    prod = event.alpha * event.beta
0.11 16.8
0.18 27.6
0.05 -23.4
-0.01 4.0
-0.42 15.1