Start learning free

LESSON 11 OF 165 · MACHINE LEARNING: PANDAS

Pick Columns and Rows

Practice

Often you need only part of a table. To keep some columns, put a list of names inside the square brackets: df[["age", "visits"]] gives back a smaller DataFrame with just those 2 columns and all the rows. One name without a list, df["age"], gives back a Series instead.

To pick rows, pandas has two tools. df.loc[rows, columns] picks by label: the labels printed on the left of the rows and the names on top of the columns. A label slice like 5:7 includes its end. df.iloc[...] picks by position, counted from 0 like a list, whatever the labels are. One row comes back as a Series, with the column names as its labels.

two = df[["age", "visits"]]   # a table: 2 columns, all rows
df.loc[5:7, ["age"]]          # labels 5, 6 and 7, column age
df.loc[8, "visits"]           # one value: label 8, column visits
df.iloc[-1]                   # the last row, by position

This time the read line adds index_col="customer_id": the customer ids become the row labels, and customer_id is no longer a column. So label 3 is customer 3, but position 3 is the fourth row, customer 4. Your script must print:

               city  spent
customer_id
1              Rome    720
2            Madrid    201
3            Madrid    257
               city   age
customer_id
1              Rome  52.0
2            Madrid  41.0
3            Madrid  51.0
city                     Rome
age                      52.0
joined             2026-09-25
newsletter                yes
visits                     11
orders                      6
spent                     720
days_since_last            21
returned_item               0
bought_again                1
Label 3: Madrid
Position 3: Lyon

Your task: below the read line, keep the city and spent columns in pair and print its first 3 rows. Print the labels 1 to 3 with the columns city and age using loc, and the row at position 0 using iloc. Then print "Label 3:" with the city at label 3, and "Position 3:" with the city at position 3.


Assignment
Follow the Coding Tutorial to pick columns with a list of names, and rows with loc (by label) and iloc (by position).


Hint
Print tables and rows with .to_string(). loc and iloc take square brackets, not parentheses. df.iloc[3] is a whole row; add ["city"] after it for one value.


STEP 1 OF 6
    Ctrl + Enter to check