15.3 C
London
Tuesday, June 17, 2025
HomePandas in PythonDataFrame Functions in PythonHow to Add a Column to a NumPy Array (With Examples)

How to Add a Column to a NumPy Array (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories