How to iterate over rows in a DataFrame in Pandas
You can use the iterrows() method to iterate over rows in a Pandas DataFrame.
You can use the iterrows() method to iterate over rows in a Pandas DataFrame. Here is an example of how to do it:
Iterate over rows in a Pandas DataFrame
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. Note that iterrows() can be slow for large DataFrames. For better performance, consider using itertuples() or vectorized operations.
You can also use the apply() method to apply a function to each row or column in the DataFrame. For example:
Using the apply() method to apply a function to each row or column in a Pandas DataFrame
df.apply(lambda row: 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). The function should return a value to be included in the resulting Series.