To loop through the rows of a Pandas DataFrame, you can use one of several methods depending on your specific needs:
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.
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.
- Using a
for
loop with the DataFrame directly: You can also loop through the columns of a DataFrame using afor
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.
- sunny asked 1 month ago
- You must login to post comments
Please login first to submit.