Pandas is a popular Python library for data analysis and manipulation. One of its main features is the DataFrame object, which represents a 2-dimensional labeled data structure with columns of potentially different types. Iterating over a Pandas DataFrame can be done in several ways, depending on what you want to achieve.

  1. Iterating over rows: 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 as Pandas Series objects. Here's an example:
import pandas as pd
 
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]})
 
for index, row in df.iterrows():
    print(f"Index: {index}, Name: {row['Name']}, Age: {row['Age']}")

Output:

Index: 0, Name: Alice, Age: 25
Index: 1, Name: Bob, Age: 30
Index: 2, Name: Charlie, Age: 35
  1. Iterating over columns: You can iterate over columns in a Pandas DataFrame using the iteritems() method. This method returns an iterator that yields pairs of column name and column data as Pandas Series objects. Here's an example:
import pandas as pd
 
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]})
 
for column, series in df.iteritems():
    print(f"Column: {column}, Data: {series.tolist()}")

Output:

Column: Name, Data: ['Alice', 'Bob', 'Charlie']
Column: Age, Data: [25, 30, 35]
  1. Vectorized operations: In most cases, iterating over a Pandas DataFrame using the above methods should be avoided because they can be slow and inefficient. Instead, Pandas provides vectorized operations that allow you to perform operations on entire columns or rows at once, which can be much faster. For example, you can use arithmetic operators or functions from the NumPy library to perform mathematical operations on entire columns. Here's an example:
import pandas as pd
import numpy as np
 
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
 
# Multiply column A by 2
df['A'] = df['A'] * 2
 
# Add 1 to column B
df['B'] = np.add(df['B'], 1)
 
print(df)

Output:

   A  B
0  2  5
1  4  6
2  6  7

In summary, Pandas provides several ways to iterate over a DataFrame, but in most cases, vectorized operations should be used for better performance.