1. Learn
  2. /
  3. Courses
  4. /
  5. Writing Efficient Code with pandas

Exercise

Row selection: loc[] vs iloc[]

A big part of working with DataFrames is to locate specific entries in the dataset. You can locate rows in two ways:

  • By a specific value of a column (feature).
  • By the index of the rows (index). In this exercise, we will focus on the second way.

If you have previous experience with pandas, you should be familiar with the .loc and .iloc indexers, which stands for 'location' and 'index location' respectively. In most cases, the indices will be the same as the position of each row in the Dataframe (e.g. the row with index 13 will be the 14th entry).

While we can use both functions to perform the same task, we are interested in which is the most efficient in terms of speed.

Instructions 1/3

undefined XP
    1
    2
    3
  • Store the indices of the first 1000 rows in the row_nums.
  • Use the .loc[] indexer to select the first 1000 rows of poker_hands, and record the times before and after that operation.
  • Print the time it took to select the rows.