Categories
Python Answers

How to add an extra column to a NumPy array with Python?

Spread the love

Sometimes, we want to add an extra column to a NumPy array with Python.

In this article, we’ll look at how to add an extra column to a NumPy array with Python.

How to add an extra column to a NumPy array with Python?

To add an extra column to a NumPy array with Python, we can use the append method.

For instance, we write:

import numpy as np
a = np.array([[1,2,3],[2,3,4]])
z = np.zeros((2,1), dtype=np.int64)
b = np.append(a, z, axis=1)
print(b)

We create the array a with np.array.

Then we call np.zeroes with the dimensions of the array passed in as a tuple and the data type set as the value of dtype.

Then we call append with a and z to append z to a.

It returns a new array and we assign that to b.

Therefore, b is:

[[1 2 3 0]
 [2 3 4 0]]

Conclusion

To add an extra column to a NumPy array with Python, we can use the append method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *