What is np.c_ and np.r_ in numpy ?

Brijesh Goyal
2 min readJan 18, 2021
Photo by John Moeses Bauan on Unsplash

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 :)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Brijesh Goyal
Brijesh Goyal

Written by Brijesh Goyal

I am a machine learning enthusiast and love to do coding. Currently on my path to explore more things.

Responses (2)

Write a response