How to iterate over Elements of Row in Pandas DataFrame?
Pandas DataFrame - Iterate over Elements of Row
To iterate over the elements of a Row in Pandas DataFrame, you can use incremental index with DataFrame.at[] or get the row and use Series.items().
Examples
1. Iterate over elements of a row in DataFrame using Index
In this example, we will
- Initialize a DataFrame with some numbers.
- Get the specific row.
- Get the number of columns.
- Use for loop to iterate over the elements.
Python Program
import pandas as pd
import numpy as np
df = pd.DataFrame(
[['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l']])
row = df.iloc[1] #index=1 => second row
length = row.size
for i in range(length):
print(row[i])
Output
d
e
f
2. Iterate over elements of a row in DataFrame using Series.items()
In this example, we will
- Initialize a DataFrame with some numbers.
- Get the specific row as Series using DataFrame.iloc property.
- Iterate over items of this row using Series.items()
Python Program
import pandas as pd
import numpy as np
df = pd.DataFrame(
[['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l']])
row = df.iloc[1] #index=1 => second row
for index, item in row.items():
print(item)
Output
d
e
f
Summary
In this tutorial of Python Examples, we learned how to iterate over elements of a specific row in Pandas DataFrame, with the help of example programs.