What is np.c_ and np.r_ in numpy ?
This is a small and easy explanation on how to use them!
It’s a handy technique for concatenation of numpy arrays using its np.c_ and np.r_
Short definition of what they do:np.c_[]
concatenates arrays along second axis.
Similarly, np.r_[]
concatenates arrays along first axis.
Confusing right ?
Let’s create 2 arrays a
and b
to learn with the example.
import numpy as npa = np.array([[1, 2, 3],
[11,22,33]]
)
b = np.array([[4, 5, 6],
[44,55,66]]
)
a’s shape: (2,3) i.e. (no. of rows, no. of columns) i.e. (1st axis, 2nd axis)
So, first axis is along the 2 rows and second axis is along the columns.
Similarly,
b’s shape: (2,3) i.e. (1st axis, 2nd axis)
np.r_ concatenates along the first axis (i.e. along 2 rows)
So, we get below result on running np.r_[a,b]
command
np.r_[a,b]
>>> array([[ 1, 2, 3],
[11, 22, 33],
[ 4, 5, 6],
[44, 55, 66]])
i.e. concatination along the rows(first axis), so number of rows will increase here to 4.
While np.c_[a,b] concatenates along the Second axis i.e. concatenation id taking place along columns and give result as below:
>>> array([[ 1, 2, 3, 4, 5, 6],
[11, 22, 33, 44, 55, 66]
])
I hope it was helpful!
You can find me on Linkedin here.
brijeshgoyal0808@gmail.com
Thanks for reading :)