The same numbers can be laid out in different shapes. np.arange(12) gives back a flat array of the whole numbers 0 to 11, shape (12,). .reshape(rows, columns) gives back the same numbers as a table, filled row by row. Rows times columns must equal the count, or numpy raises a ValueError.
Write -1 for one size and numpy works it out: .reshape(-1, 1) means one column, as many rows as it takes. That is the shape scikit-learn wants for a single feature: one row per customer, one column for the feature. np.column_stack takes a list of flat arrays and gives back one 2-D array with each of them as a column.
ages = np.array([25, 41, 33])
kids = np.array([0, 2, 1])
grid = np.arange(8).reshape(2, 4) # rows [0 1 2 3] and [4 5 6 7]
col = ages.reshape(-1, 1) # shape (3, 1): 3 rows, 1 column
both = np.column_stack([ages, kids]) # rows [25 0], [41 2], [33 1]
print(both.shape) # (3, 2)
In this lesson, visits and spent hold the visits and spending of 4 customers. The starting code prints numbers and the shape of visits. When you're done, the program prints:
Numbers: [ 0 1 2 3 4 5 6 7 8 9 10 11] [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Visits shape: (4,) [[ 3] [ 8] [ 1] [12]] Column shape: (4, 1) [[ 3 40] [ 8 95] [ 1 12] [ 12 180]]
Your task: print numbers reshaped into 3 rows of 4, reshape visits into one column called column and print it with its shape, then stack visits and spent side by side with np.column_stack into table and print it.
Assignment
Follow the Coding Tutorial to reshape numbers into a grid, turn visits into a column and stack two arrays into a table.
Hint.reshape gives back a new array and leaves the original as it was, so visits stays (4,). np.column_stack takes one argument, a list: put both arrays inside square brackets.
Free plan: 30 tutor messages. PRO is unlimited.
