Iteration over Dataframe and Series.#

  • iteritems(): Helps to iterate over each element of the set, column-wise.

  • iterrows(): Each element of the set, row-wise.

  • itertuple(): Each row and form a tuple out of them.

[2]:
# import pandas and numpy library
import pandas as pd
import numpy as np

# List of Tuples
matrix = [(1, 2, 3),
            (4, 5, 6),
            (7, 8, 9)
            ]

# Create a DataFrame object
df = pd.DataFrame(matrix, columns = list('xyz'),
                            index = list('abc'))
display(df)


#### Applying


x y z
a 1 2 3
b 4 5 6
c 7 8 9
[7]:
for index,row in df.iterrows():
    print(row['x'])
1
4
7
[10]:
for index,col in df.iteritems():
    print(index,'\n',col)
x
 a    1
b    4
c    7
Name: x, dtype: int64
y
 a    2
b    5
c    8
Name: y, dtype: int64
z
 a    3
b    6
c    9
Name: z, dtype: int64