Python

NumPy np.c_

The NumPy np.c_ is part of the NumPy’s indexing routines that allow you to concatenate an array along the second axis.

Let us explore how this routine works and how we can use it.

Syntax

The syntax of the numpy c_ routine is as shown below:

numpy.c_[arrays]

Return Value

The routine does not take any parameters except the arrays that you need to concatenate.

It will then return the concatenated array along the second axis.

Example Illustration

The example below illustrates how to use the np.c_ to concatenate two arrays.

# import numpy
import numpy as np
# create an array
arr1 = np.array([1,2,3])
arr2 = np.array([7,8,9])
print(np.c_[arr1, arr2])

In this example, the np.c_ routine takes the arrays and concatenates them along the second axis.

NOTE: When talking about the second axis, we refer to the axis=1 or the column axis.

The code above should return an array as:

[[1 7]
 [2 8]
 [3 9]]

In this case, the np.c_ takes two one-dimensional arrays and concatenates them to form a two-dimensional array.

Example #2

Let us see what happens when we apply the routine in 2d arrays.

arr1 = np.array([[1,2,3,4], [5,6,7,8]])
arr2 = np.array([[9,10,11,12], [13,14,15,16]])
print(np.c_[arr1, arr2])

The code snippet above should return:

[[ 1  2  3  4  9 10 11 12]
 [ 5  6  7  8 13 14 15 16]]

Closing

This article aims to help you understand NumPy’s indexing routine np.c_ and how to use it.

Thanks for reading!!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list