How can I loop through the rows of a Pandas DataFrame?

0
0

To loop through the rows of a Pandas DataFrame, you can use one of several methods depending on your specific needs:

  1. iterrows(): This method allows you to iterate over the rows of a DataFrame as (index, Series) pairs, where the Series contains the data for each row. Here’s an example:

import pandas as pd

df = pd.DataFrame({‘A’: [1, 2, 3], ‘B’: [4, 5, 6]})

for index, row in df.iterrows():
print(index, row[‘A’], row[‘B’])

 

Note that iterrows() can be slower than other methods because it returns a new Series object for each row.

  1. itertuples(): This method returns an iterator that yields namedtuples containing the values of each row. Here’s an example:

import pandas as pd

df = pd.DataFrame({‘A’: [1, 2, 3], ‘B’: [4, 5, 6]})

for row in df.itertuples():
print(row.Index, row.A, row.B)

 

Note that itertuples() can be faster than iterrows() because it doesn’t create a new Series object for each row.

 

  1. Using a for loop with the DataFrame directly: You can also loop through the columns of a DataFrame using a for loop and index the DataFrame directly to access the values in each row. Here’s an example:

import pandas as pd

df = pd.DataFrame({‘A’: [1, 2, 3], ‘B’: [4, 5, 6]})

for i in range(len(df)):
print(df.loc[i, ‘A’], df.loc[i, ‘B’])

Note that this method can be slower than iterrows() and itertuples() for large DataFrames, because indexing the DataFrame for each row can be slow.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.