w3resource

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


Add Extra Column to Array

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: