You can iterate over rows in a Pandas DataFrame using the iterrows()
method. This method returns an iterator that yields pairs of index and row data, where the row data is a Pandas Series object.
Here's an example of how to use iterrows()
to iterate over rows in a DataFrame:
pythonimport pandas as pd
# create a sample DataFrame
data = {'name': ['Alice', 'Bob', 'Charlie', 'David'],
'age': [25, 30, 35, 40],
'city': ['New York', 'Paris', 'London', 'Tokyo']}
df = pd.DataFrame(data)
# iterate over rows in the DataFrame
for index, row in df.iterrows():
print(index, row['name'], row['age'], row['city'])
Output:
sql0 Alice 25 New York
1 Bob 30 Paris
2 Charlie 35 London
3 David 40 Tokyo
In this example, we're iterating over the rows in the DataFrame df
using the iterrows()
method. For each row, we're printing the index value and the values of the name
, age
, and city
columns.
Note that while iterrows()
is a useful method for iterating over rows in a DataFrame, it can be slower than other methods for certain operations. If you're performing vectorized operations on a DataFrame, it's generally better to use built-in Pandas functions or NumPy functions to avoid the overhead of iterating over each row.
Comments
Post a Comment