Merging Rows and Columns in numpy array in Python
Code
import numpy as np
a = np.array([[1,2,3]])
b = np.array([[4,5,6]])
print(a)
print(b)
print(np.c_[a,b])
print(np.r_[a,b])
Python’s numpy
package offers many convenient features. As seen in the following screenshot, objects numpy.c_
and numpy.r_
merge arrays contained within brackets [] as columns and rows, respectively. It’s important to clarify that these are not methods. They may be used like methods, but they are simply arrays that have already been merged using brackets []. This can be syntactically confusing, so it’s crucial to understand this at least once thoroughly to quickly find errors.
Another thing to note is that when creating arrays, they were made by using double brackets, i.e., [[]]. In this way, as per our intuition, it was possible to implement the desired column and row merges. On the other hand, consider the following code, which creates arrays with a single set of brackets [] and observe the outcome.
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
print(a)
print(b)
print(np.c_[a,b])
print(np.r_[a,b])
The intuitive result above and the difference below lie in whether it’s a 1-dimensional array or a 2-dimensional array. In the former case, the concept of rows and columns is already visible to us at the stage of creating the array, but in the latter case, since it transitions to a vector, it appears differently than what we see. This implementation is understandably attributed to the fact that the numpy package is specialized in mathematics.
$$
\overrightarrow{v} = (\pi , 0.7) = \begin{bmatrix}
\pi
\\ 0.7
\end{bmatrix}
$$
For instance, a vector $\overrightarrow{v}$ on the coordinate plane, that is, in the $2$-dimensional Euclidean space, is a vector with $2$ components (1-dimensional array) and at the same time a $\overrightarrow{v} \in \mathbb{R}^{2 \times 1}$ matrix (2-dimensional array), thus both representations can be used. In the case of the numpy
package, it follows the convention of matrices―and further, tensors, to accommodate more general expressions.