Here's an example of how to use .itertuples() to iterate through a Pandas DataFrame row by row:
import pandas as pd# Create an example DataFramedf = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'Gender': ['Female', 'Male', 'Male']})# Iterate through each row using .itertuples()for row in df.itertuples(): print(row) |
Output:
Pandas(Index=0, Name='Alice', Age=25, Gender='Female')Pandas(Index=1, Name='Bob', Age=30, Gender='Male')Pandas(Index=2, Name='Charlie', Age=35, Gender='Male') |
In this example, we create an example DataFrame with columns for Name, Age, and Gender. We then use a for loop to iterate through each row of the DataFrame using .itertuples(). The loop prints out each row as a named tuple, which contains the index and values for each column in the DataFrame.
You can access the values of each column in the named tuple using dot notation. For example, to access the Name column, you can use row.Name. Note that the index of the DataFrame is included in the named tuple as the Index field, which you can access using row.Index.