How to add a new column of nan values in an array (matrix) with numpy in python ?

Published: March 24, 2021

Tags: Python; Numpy;

DMCA.com Protection Status

Examples of how to add a new column of nan values in a matrix with numpy:

Create an array

Let's first create an array with numpy

import numpy as np

A = np.arange(20)

A = A.reshape(5,4)

A = A.astype('float64')

returns

array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5.,  6.,  7.],
       [ 8.,  9., 10., 11.],
       [12., 13., 14., 15.],
       [16., 17., 18., 19.]])

Create a column of nan

new_col = np.empty((A.shape[0],1))
new_col.fill(np.nan)

new_col

returns

array([[nan],
       [nan],
       [nan],
       [nan],
       [nan]])

Add a column of nans values in first column

new_A = np.c_[new_col,A]

new_A

returns

array([[nan,  0.,  1.,  2.,  3.],
       [nan,  4.,  5.,  6.,  7.],
       [nan,  8.,  9., 10., 11.],
       [nan, 12., 13., 14., 15.],
       [nan, 16., 17., 18., 19.]])

Add a column of nans in last column

new_A = np.c_[A,new_col]

new_A

returns

array([[ 0.,  1.,  2.,  3., nan],
       [ 4.,  5.,  6.,  7., nan],
       [ 8.,  9., 10., 11., nan],
       [12., 13., 14., 15., nan],
       [16., 17., 18., 19., nan]])

Add a column of nans for a given index

new_A = np.insert(A,2,new_col.T,axis=1)

new_A

returns

array([[ 0.,  1., nan,  2.,  3.],
       [ 4.,  5., nan,  6.,  7.],
       [ 8.,  9., nan, 10., 11.],
       [12., 13., nan, 14., 15.],
       [16., 17., nan, 18., 19.]])

References