Menu
CoddyTech

Joining Arrays

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 17 of 60.

A museum counted visitors on three mornings, then on two evenings. np.concatenate joins arrays end to end:

Five cells in one row: the morning counts 12, 15, 19 followed by the evening counts 20, 18

The code:

morning = np.array([12, 15, 19])
evening = np.array([20, 18])
print(np.concatenate([morning, evening]))

This prints [12 15 19 20 18]. A model wants something else: one row per sample, one column per feature. np.column_stack puts arrays side by side as columns:

A table of 3 flats in 2 columns: sizes 45, 60, 82 next to rents 900, 1200, 1500, one flat per row

In code:

sizes = np.array([45, 60, 82])
rents = np.array([900, 1200, 1500])
table = np.column_stack([sizes, rents])
print(table.shape)

This prints (3, 2). Each row takes a value from every array, so their lengths must match.

challenge icon

Challenge

Easy

A study needs one table of people: age in the first column, daily screen hours in the second, group 1 first. A colleague's code stops with an error, and once that is fixed, the table still comes out wrong.

Fix the three lines that build ages, hours and table. Keep the last two lines as they are.

For a smaller study of three people, the fixed program prints:

[[30  5]
 [28  8]
 [62  2]]
People: 3, measurements each: 2

Try it yourself

import numpy as np

# First group: each person's age and daily screen time in hours
ages_1 = np.array([23, 35, 41])
hours_1 = np.array([6, 4, 3])
# Second group
ages_2 = np.array([19, 52])
hours_2 = np.array([7, 2])

# The study needs one row per person: age, then hours. Fix the lines below
ages = np.concatenate([ages_1, ages_2])
hours = np.concatenate(hours_1, hours_2)
table = np.concatenate([ages, hours])

# Don't change the lines below
print(table)
print(f"People: {table.shape[0]}, measurements each: {table.shape[1]}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler