Numpy np.ma.concatenate() method-Python
np.ma.concatenate() method joins two or more masked arrays along an existing axis. It works similarly to np.concatenate() but it is specifically designed for masked arrays which may contain missing or invalid data that is "masked" i.e marked to be ignored in computations.
Example:
import numpy as np
a = np.ma.array([1, 2, 3], mask=[0, 1, 0])
b = np.ma.array([4, 5, 6], mask=[0, 0, 1])
res = np.ma.concatenate([a, b])
print(res)
Output
[1 -- 3 4 5 --]
Arrays a and b contain some masked elements (2 and 6). The method joins them into one array while preserving the masked values (--) which represent data to be ignored during calculations.
Syntax
np.ma.concatenate(arrays, axis=0)
Parameters:
- arrays: A sequence (e.g., list or tuple) of masked arrays to be joined.
- axis (int, optional): The axis along which the arrays will be joined. Default is 0.
Returns: A new masked array formed by concatenating the input arrays.
Examples
Example 1: In this example, we are concatenating two 2D masked arrays along axis=1, which means horizontally (column-wise).
import numpy as np
a = np.ma.array([[1, 2], [3, 4]], mask=[[0, 1], [0, 0]])
b = np.ma.array([[5, 6], [7, 8]], mask=[[0, 0], [1, 0]])
res = np.ma.concatenate([a, b], axis=1)
print(res)
Output
[[1 -- 5 6] [3 4 -- 8]]
Array a has 2 masked and b has 7 masked. np.ma.concatenate([a, b], axis=1) joins them column-wise resulting in [[1 -- 5 6], [3 4 -- 8]] with masked values (--) preserved.
Example 2: In this example we are concatenating two 2D masked arrays along axis=0, which means vertically (row-wise).
import numpy as np
a = np.ma.array([[10], [20]], mask=[[0], [1]])
b = np.ma.array([[30], [40]], mask=[[0], [0]])
res = np.ma.concatenate([a, b], axis=0)
print(res)
Output
[[10] [--] [30] [40]]
Here array a has 20 masked. We join the arrays vertically (axis=0) so rows from b are stacked below a. The masked value (--) remains intact.
Example 3: In this example, we vertically concatenate two masked 2D arrays along axis=0 which means stacking them row-wise.
import numpy as np
a = np.ma.array([[100, 200], [300, 400]], mask=[[0, 1], [0, 0]])
b = np.ma.array([[500, 600]], mask=[[1, 0]])
res = np.ma.concatenate([a, b], axis=0)
print(res)
Output
[[100 --] [300 400] [-- 600]]
Array a has 200 masked and b has 500 masked. Joining along axis=0 stacks rows of b below a. The result is a vertically combined array with all masked values preserved.