concatenate joins along an existing axis. stack adds a new axis. split is the inverse.
Goal
Build a small summary table from city totals and rainfall, and split a year into quarters.
concatenate along rows
nairobi = np.array([[12, 7, 2]], dtype=float)
mombasa = np.array([[9, 6, 0]], dtype=float)
print(np.concatenate([nairobi, mombasa], axis=0))hstack / vstack
revenue = np.array([126.0, 154.0, 62.0], dtype=float)
apr = np.array([150.0, 90.0, 180.0], dtype=float)
table = np.column_stack([revenue, apr])
print(table)
print("shape:", table.shape)Columns: city revenue total, April rain. Rows still Nairobi, Mombasa, Kisumu.
stack adds an axis
jan = np.array([50, 20, 70], dtype=float)
feb = np.array([40, 15, 80], dtype=float)
print("stack axis=0:", np.stack([jan, feb], axis=0).shape)
print(np.stack([jan, feb], axis=0))
print()
print("stack axis=1:", np.stack([jan, feb], axis=1).shape)
print(np.stack([jan, feb], axis=1))concatenate on 1-D always stays 1-D. stack is how you make a new dimension.
split
year = np.arange(12, dtype=float)
q1, q2, q3, q4 = np.split(year, 4)
print(q1, q2, q3, q4)The array must divide evenly. Use array_split if the lengths may differ.
Tip
column_stack is the readable way to glue 1-D summaries into a 2-D report before savetxt.