Pandas · Select rows with loc and iloc
Google Search Analytics
Course overviewGoogle Search · Work with DataFrames

Select rows with loc and iloc

Select by index label or row position without confusing the two.

Step 1 of 3 · Learn

Select by label

loc selects index labels. The workspace provides indexed_searches, created with searches.set_index("search_id"). Search IDs become index labels instead of a data column.

indexnamescore
10Ari12
20Bo18
40Cam9
indexnamescore
20Bo18
40Cam9
Labels 20 and 40 select the second and third rows.

Select by position

iloc counts positions from zero. Its slice excludes the stop position. On this sorted index, loc[10:20] includes both endpoint labels, while iloc[0:2] selects positions 0 and 1.

indexnamescore
10Ari12
20Bo18
40Cam9
indexnamescore
10Ari12
20Bo18
Positions start at zero, regardless of the index labels.
▷ Your turn

From indexed_searches, return search IDs 1001 and 1007, in that order. Keep every data column and preserve search_id as the index. Save the DataFrame as result.

Also available: indexed_searches, indexed by search_id.

LANGUAGEPython · Pandas

Loading Python and Pandas…

Run the code to see DataFrame results here.