Home > Backend Development > Python Tutorial > How Can I Iterate Over Rows in a Pandas DataFrame?

How Can I Iterate Over Rows in a Pandas DataFrame?

Patricia Arquette
Release: 2024-12-22 19:19:21
Original
785 people have browsed it

How Can I Iterate Over Rows in a Pandas DataFrame?

Iterating Over Rows in Pandas DataFrame

In Pandas, the iterrows() method provides a convenient way to iterate over the rows of a DataFrame. This method generates a tuple for each row, where the first element is the row index and the second element is a Pandas Series containing the row's values.

Consider the following DataFrame:

   c1   c2
0  10  100
1  11  110
2  12  120
Copy after login

To iterate over the rows using iterrows(), use the following syntax:

for index, row in df.iterrows():
    print(row['c1'], row['c2'])
Copy after login

This code prints the values of the 'c1' and 'c2' columns for each row:

10 100
11 110
12 120
Copy after login

Understanding the Row Object

The row object returned by iterrows() is a Pandas Series that represents a single row of the DataFrame. It provides access to the row's values by column name, index, and label. For example:

print(row)  # prints the entire row as a Series
print(row['c1'])  # prints the value of the 'c1' column
print(row.index)  # prints the row's index
print(row.name)  # prints the row's label
Copy after login

Performance Considerations

Iterating over pandas objects can be slow, especially for large datasets. If performance is critical, consider using vectorized operations or applying functions to the DataFrame instead. However, iterrows() remains a useful tool for performing iterative operations that cannot be vectorized.

The above is the detailed content of How Can I Iterate Over Rows in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template