You can use one of the following methods to add a column to a NumPy array:
Method 1: Append Column to End of Array
np.append(my_array, [[value1], [value2], [value3], ...], axis=1)
Method 2: Insert Column in Specific Position of Array
np.insert(my_array, 3, [value1, value2, value3, ...], axis=1)
The following examples show how to use each method in practice.
Example 1: Append Column to End of NumPy Array
Suppose we have the following NumPy array:
import numpy as np #create NumPy array my_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) #view NumPy array my_array array([[1, 2, 3, 4], [5, 6, 7, 8]])
We can use the following syntax to add a column to the end of the NumPy array:
#append column to end of NumPy array
new_array = np.append(my_array, [[10], [13]], axis=1)
#view updated array
new_array
array([[ 1, 2, 3, 4, 10],
[ 5, 6, 7, 8, 13]])
Example 2: Insert Column in Specific Position of NumPy Array
Suppose we have the following NumPy array:
import numpy as np #create NumPy array my_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) #view NumPy array my_array array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
We can use the following syntax to insert a new column before the column in index position 2 of the NumPy array:
#insert new column before column in index position 2
new_array = np.insert(my_array, 2, [10, 13, 19], axis=1)
#view updated array
new_array
array([[ 1, 2, 10, 3],
[ 4, 5, 13, 6],
[ 7, 8, 19, 9]])
Notice that the new column of values has been inserted before the column in index position 2.
Additional Resources
The following tutorials explain how to perform other common operations in NumPy:
How to Add a Numpy Array to a Pandas DataFrame
How to Convert Pandas DataFrame to NumPy Array