How to concatenate arrays in python

Published on Aug. 22, 2023, 12:16 p.m.

To concatenate arrays in Python, you can use the numpy.concatenate() function if you have NumPy arrays, or the + operator if you have lists. Here are some examples:

For NumPy arrays:

import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.concatenate([a, b])
print(c)

This will output [1 2 3 4 5 6], which indicates that the arrays have been concatenated along the first axis.

If you have arrays with different dimensions, you can specify the axis parameter to indicate the axis along which to concatenate the arrays. For example:

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

This will output [[1 2] [3 4] [5 6]], which indicates that the arrays have been concatenated vertically along the first axis.

For regular Python lists, you can simply use the + operator to concatenate them:

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)

This will output [1, 2, 3, 4, 5, 6], which indicates that the lists have been concatenated.

Note that if you are concatenating lists or arrays of different types, you may need to perform some type conversion to ensure that the concatenated result is of the desired type.

Tags: