Start learning free

LESSON 31 OF 165 · MACHINE LEARNING: YOUR FIRST MODEL

Features and a Label in Python

Practice

A model learns from examples. Each example is one row of a table: some columns you know about a customer, the features, and one column you want to predict, the label. The features are called X and the label y. Here the label is bought_again: 1 if the customer came back and bought again, 0 if not.

Picking columns: double brackets with a list of names, df[["age", "visits"]], give back a smaller DataFrame with only those columns. Single brackets with one name, df["newsletter"], give back a Series: one column with its row labels. .shape gives back the size: (rows, columns) for a DataFrame, (rows,) for a Series.

info = df[["age", "visits"]]
answer = df["newsletter"]
print(info.shape)    # (300, 2)
print(answer.shape)  # (300,)

Picking columns keeps every row, and X and y keep the file's row labels, so row 1 of X and row 1 of y are the same customer. A model learns the link between them from rows where the answer is known, then guesses y for customers where only X is known. So the label must never be among the features: a new customer doesn't have it yet.

The starting code reads customers.csv with pd.read_csv and prints its shape. When you are done, your code prints:

All data: (300, 11)
X: (300, 5)
y: (300,)
   visits  orders  spent  days_since_last  returned_item
0      11       6    720               21              0
1       7       3    201               12              0
2       5       3    257                1              0
0    1
1    0
2    1

After your lines, the check prints whether the label is among the features and whether X and y have the same rows.

Your task: keep the five features visits, orders, spent, days_since_last and returned_item in X and the label bought_again in y, then print both shapes and the first 3 rows of each with .head(3).to_string().


Assignment
Follow the Coding Tutorial to split the customers table into the features X and the label y.


Hint
Two brackets for several columns (a DataFrame), one bracket for one column (a Series). .head(3) gives back the first 3 rows, and .to_string() turns them into text that prints in full.


STEP 1 OF 6
    Ctrl + Enter to check

    Ml Features Label in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free