7.4. Methods Concatenation

7.4.1. 1-dimensional Array

>>> import numpy as np
>>>
>>>
>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>>
>>> np.concatenate(a, b)
Traceback (most recent call last):
TypeError: only integer scalar arrays can be converted to a scalar index
>>>
>>> np.concatenate((a, b))
array([1, 2, 3, 4, 5, 6])
>>> import numpy as np
>>>
>>>
>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> c = np.array([7, 8, 9])
>>>
>>> np.concatenate((a, b, c))
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> import numpy as np
>>>
>>>
>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>>
>>> np.concatenate((a, b))
array([1, 2, 3, 2, 3, 4])

7.4.2. 2-dimensional Array

>>> import numpy as np
>>>
>>>
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6], [7, 8]])
>>>
>>> np.concatenate((a, b))
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])
>>>
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])
>>>
>>> np.concatenate((a, b), axis=1)
array([[1, 2, 5, 6],
       [3, 4, 7, 8]])

7.4.3. Assignments

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Numpy Concatenation
# - Difficulty: easy
# - Lines: 1
# - Minutes: 3

# %% English
# 1. Given are one-dimensional: `a: np.ndarray`, `b: np.ndarray`
# 2. Concatenate them as `result: np.ndarray`
# 3. Reshape `result` into two rows and three columns
# 4. Run doctests - all must succeed

# %% Polish
# 1. Dane są jednowymiarowe: `a: np.ndarray`, `b: np.ndarray`
# 2. Połącz je ze sobą jako `result: np.ndarray`
# 3. Przekształć `result` w dwa wiersze na trzy kolumny
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is np.ndarray, \
'Variable `result` has invalid type, expected: np.ndarray'

>>> result
array([[1, 2, 3],
       [4, 5, 6]])
"""

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Concatenate `a` and `b` and reshape as 2 by 3
# type: np.ndarray
result = ...