NumPy | How Do I Add An Extra Column To A NumPy Array?

In this Tutorial, we will learn more about How To Add An Extra Column To A NumPy Array which we can do using two different ways which are using numpy. concatenate is somewhat the same as concatenating two arrays and numpy.vstack method.

 NumPy

NumPy

Numpy is a large library in python that deals with single and multi dimensional arrays and it provides a large range of operations that we can implement on arrays to get the desired output. But here we are going to discuss how we can add a new column to an array.

Adding an extra column

We can perform this action using two different manners so here we will explore both possible ways to do so.

numpy. concatenate

It is a way to add an extra column to an existing array as we are contacting two arrays to get a clear idea following the example given below.

import numpy as np

# Initial array
array_1 = np.array([[1, 2, 3], [4, 5, 6]])

# Column to be added
column = np.array([[7], [8]])

# Concatenate the arrays vertically using np.concatenate
array_2 = np.concatenate((array_1, column), axis=1)

print(array_2)

here we simply concatenate an extra column. And the answer to the above code will be [[1 2 3 7] [4 5 6 8]].

Now let’s discuss another way to do the same thing using numpy. vstack method

numpy.vstack

In this method, we simply concatenate two arrays horizontally to understand it in a better way just follow the code given below and understand to learn and implement.

import numpy as np

# Initial array
array_1 = np.array([[1, 2, 3], [4, 5, 6]])

# Column to be added
column = np.array([[7], [8]])

# Concatenate the arrays horizontally using np.hstack
array_2 = np.hstack((array_1, column))

print(array_2)

The output of this will also be the same as the last as [[1 2 3 7]
[4 5 6 8]] as we did the same thing but with a different method.

 

To learn more about How Do I Add An Extra Column To A NumPy Array visit Numpy operations to add a new column in python.

Also, visit Understanding Python Dictionary Slicing – Detailed Tutorial with Examples and Problems   to learn more about numpy and to learn more about different programming languages visit beta python for programming Solutions

Leave a Comment

%d bloggers like this: