Python Pandas For Loop

Geomario
2 min readOct 21, 2020

When to use Python Pandas For Loop? There are at least 5 methods to loop over a DataFrame, today; we explain python pandas for loop with iterrows().

A Loop!

The DataFrame structure, it's always associated with an index. In the same way, the Pandas Series. The index helps us to perform operations within the DataFrame. The iterrows() generator, loop from the index and extract the row values of the DataFrame.


#Code block 1.0
for index, row in df.iterrows(): #(1)
print (index, row) #(2)

In the code block 1.0, we loop from the index and row over the dataframe, df (1). In the next line (2), we print the row and index values from the dataframe.

#Code block 2.0>>>0 foo      one    #(1)
bar A
s_baz 1
zoo x

The result in code block 2.0 shows the results from the code block 1.0. The result (1) is the first iteration over the DataFrame, which corresponds to the index 0 in the dataframe with the values correspondent to that row.

What happens when we want to extract the column and not the row from the Pandas DataFrame?

#Code block 3.0for index, row in df.iterrows():
print (row["foo"]) #(1)

In the code block 3.0, we loop over the dataframe and provide the column name that we want to extract (1). The result from this iteration corresponds to the column “foo” from the data frame.

#Code block 4.0>>>
one
one
one
two
two
two

The result in code block 4.0, corresponds to the column “Foo”. There are some other methods that we could add better to see how they work while coding. Give it a try to my video. For real, they are amazing! Do follow us and subscribe! Please?

Thank you & Happy coding!

--

--

Geomario

👨‍💻 Software & Data Developer | Software Research Engineer | MLE