How to iterate over rows in a DataFrame in Pandas
You can use the iterrows()
method to iterate over rows in a Pandas DataFrame. Here is an example of how to do it:
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# Iterate over rows in the DataFrame
for index, row in df.iterrows():
# Access data for each column by column name
print(index, row['A'], row['B'], row['C'])
This will print the index and the values for each column for each row.
You can also use the apply()
method to apply a function to each row or column in the DataFrame. For example:
df.apply(lambda row: print(row['A'], row['B'], row['C']), axis=1)
This will apply the function to each row in the DataFrame, and the axis=1
argument specifies that the function should be applied to each row, rather than to each column (which is the default behavior).