# How to add a column to a NumPy array in Python

Hello folks, in this tutorial we are going to learn how to add a column to a NumPy array in Python language. Two methods are discussed below.

It is obvious that we need to import NumPy library before we begin.

To know more about NumPy arrays,refer this

## Using append or insert to add a column to a NumPy array in Python

Method-1 (Using append method):

Append method requires three parameters:

- Original array – The array to which we wanted to add a column
- New Values – The values of the column we wanted to add
- Axis – The axis by which we wanted to append, this is always 1 in this case

Let’s look into an example

arr = [[1,2,3] , [4,5,6] , [7,8,9]]

newcolumn = [[99],[100],[101]]

import numpy as np original = [[1,2,3],[4,5,6],[7,8,9]] arr = np.array(original) print("The original array is :") print(arr) print("--------------------------") newcolumn = [[99],[100],[101]] newarray=np.append(arr,newcolumn,axis=1) print("Array after adding a column:") print(newarray)

Output:

The original array is : [[1 2 3] [4 5 6] [7 8 9]] -------------------------- Array after adding a column: [[ 1 2 3 99] [ 4 5 6 100] [ 7 8 9 101]]

#### Method – 2 (Using insert method):

Insert method helps in adding the column at any position as per the requirement. It requires 4 parameters. They are:

- Original array – The array to which we wanted to add a column
- Index – The position where we want to add a column
- Values – Values of the new column
- Axis-The axis by which we wanted to append, this is always 1 in this case

Example:

arr = [[1,2,3] , [4,5,6] , [7,8,9]]

newcolumn = [99,100,101]

To add the newcolumn in the second position, we need to assign 1 for index parameter

index = 1

import numpy as np original = [[1,2,3],[4,5,6],[7,8,9]] arr = np.array(original) print("The original array is :") print(arr) print("--------------------------") newcolumn = [99,100,101] index=1 newarray=np.insert(arr,index,newcolumn,axis=1) print("Array after adding a column:") print(newarray)

Output:

The original array is : [[1 2 3] [4 5 6] [7 8 9]] -------------------------- Array after adding a column: [[ 1 99 2 3] [ 4 100 5 6] [ 7 101 8 9]]

Also read: How to use numpy.percentile() in Python

## Leave a Reply