w3resource

NumPy: How to add an extra column to a NumPy array

NumPy: Array Object Exercise-86 with Solution

Write a NumPy program to add an extra column to a NumPy array.

Pictorial Presentation:

Python NumPy: How to add an extra column to a NumPy array

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' with a shape of 2x3 (2 rows, 3 columns)
x = np.array([[10, 20, 30], [40, 50, 60]])

# Creating a NumPy array 'y' with a shape of 2x1 (2 rows, 1 column)
y = np.array([[100], [200]])

# Appending arrays 'x' and 'y' along the second axis (axis=1), concatenating them horizontally
# The resulting array will have a shape of 2x4 (2 rows, 4 columns)
print(np.append(x, y, axis=1)) 

Sample Output:

[[ 10  20  30 100]                                                     
 [ 40  50  60 200]]

Explanation:

‘x = np.array([[10,20,30], [40,50,60]])’ creates a 2x3 NumPy array 'x' with elements [[10, 20, 30], [40, 50, 60]].

‘y = np.array([[100], [200]])’ creates a 2x1 NumPy array 'y' with elements [[100], [200]].

print(np.append(x, y, axis=1)): Call the np.append() function to append the 'y' array to the 'x' array along the horizontal axis (axis=1). The resulting array will have the same number of rows as both 'x' and 'y', and its columns will be the combined columns of 'x' and 'y'.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create a NumPy array of 10 integers from a generator.
Next: Write a NumPy program to find unique rows in a NumPy array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-86.php