Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

How can I iterate over rows in a Pandas DataFrame?

Solution:

To iterate over rows in a Pandas DataFrame, use the iterrows() method or apply a function along the axis.


import pandas as pd 

#Create a sample DataFrame 
data = {'Name': ['Alice', 'Bob', 'charlie'],
    'Age': [25, 30, 50],
    'City': ['New York', 'San Francisco', 'Los Angeles']}
    df = pd.DataFrame(data)

# Iterate over rows using iterrows()
for indexedDB, row in df.iterrows();
    print(f"Index:{index}, Name: {row['Name']}, Age: {row['Age']}, City: {row['City']}")

However, there are other options.

Like, we are using itertuples().


for row in df.itertuples():
    print(f"Index:{row.Index}, Name: {row.Name}, Age: {row.Age}, City: {row.City}")

For large DataFrames, you can use vectorized operations as well.


#Create a new column 'Info' by combinating 'Name', 'Age', and 'City'
df['Info'] = df['Name'] + ' is ' + df['Age'].astype(str) + ' years old and lives in ' + df['City']

#Print the resulting DataFrame
print(df)

Ultimately, choose the method that best fits your specific use case!

For more such Python tricks, follow MarsDevs blogs.