Get Started

Create a generator for a pandas DataFrame

As you've seen in the video, you can easily create a generator out of a pandas DataFrame. Each time you iterate through it, it will yield two elements:

  • the index of the respective row
  • a pandas Series with all the elements of that row

You are going to create a generator over the poker dataset, imported as poker_hands. Then, you will print all the elements of the 2nd row, using the generator.

Remember you can always explore the dataset and see how it changes in the IPython Shell, and refer to the slides in the Slides tab.

This is a part of the course

“Writing Efficient Code with pandas”

View Course

Exercise instructions

  • Assign a generator over the rows of the data dataset on the variable generator.
  • Print all the elements of the 2nd element of the created generator.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Create a generator over the rows
generator = poker_hands.____

# Access the elements of the 2nd row
first_element = next(generator)
second_element = ____(____)
print(first_element, second_element)
Edit and Run Code

This exercise is part of the course

Writing Efficient Code with pandas

IntermediateSkill Level
4.5+
11 reviews

Learn efficient techniques in pandas to optimize your Python code.

This chapter presents different ways of iterating through a Pandas DataFrame and why vectorization is the most efficient way to achieve it.

Exercise 1: Looping using the .iterrows() functionExercise 2: Create a generator for a pandas DataFrame
Exercise 3: The iterrows() function for loopingExercise 4: Looping using the .apply() functionExercise 5: .apply() function in every cellExercise 6: .apply() for rows iterationExercise 7: Vectorization over pandas seriesExercise 8: Why vectorization in pandas is so fast?Exercise 9: pandas vectorization in actionExercise 10: Vectorization with NumPy arrays using .values()Exercise 11: Best method of vectorizationExercise 12: Vectorization methods for looping a DataFrame

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free