Add columns in the Numpy array
Method 1: Using np.append()
Python3
import numpy as np ini_array = np.array([[ 1 , 2 , 3 ], [ 45 , 4 , 7 ], [ 9 , 6 , 10 ]]) # printing initial array print ( "initial_array : " , str (ini_array)); # Array to be added as column column_to_be_added = np.array([[ 1 ], [ 2 ], [ 3 ]]) # Adding column to array using append() method arr = np.append(ini_array, column_to_be_added, axis = 1 ) # printing result print ( "resultant array" , str (arr)) |
Output:
initial_array : [[ 1 2 3] [45 4 7] [ 9 6 10]] resultant array [[ 1 2 3 1] [45 4 7 2] [ 9 6 10 3]]
Method 2: Using np.concatenate
Python3
import numpy as np ini_array = np.array([[ 1 , 2 , 3 ], [ 45 , 4 , 7 ], [ 9 , 6 , 10 ]]) # Array to be added as column column_to_be_added = np.array([[ 1 ], [ 2 ], [ 3 ]]) # Adding column to array using append() method arr = np.concatenate([ini_array, column_to_be_added], axis = 1 ) # printing result print ( "resultant array" , str (arr)) |
Output:
resultant array [[ 1 2 3 1] [45 4 7 2] [ 9 6 10 3]]
Method 3: Using np.insert()
Python3
import numpy as np ini_array = np.array([[ 1 , 2 , 3 ], [ 45 , 4 , 7 ], [ 9 , 6 , 10 ]]) # Array to be added as column column_to_be_added = np.array([[ 1 ], [ 2 ], [ 3 ]]) # Adding column to array using append() method arr = np.insert(ini_array, 0 , column_to_be_added, axis = 1 ) # printing result print ( "resultant array" , str (arr)) |
Output:
resultant array [[ 1 2 3 1] [45 4 7 2] [ 9 6 10 3]]
Method 4: Using np.hstack()
Python3
import numpy as np ini_array = np.array([[ 1 , 2 , 3 ], [ 45 , 4 , 7 ], [ 9 , 6 , 10 ]]) # Array to be added as column column_to_be_added = np.array([ 1 , 2 , 3 ]) # Adding column to numpy array result = np.hstack((ini_array, np.atleast_2d(column_to_be_added).T)) # printing result print ( "resultant array" , str (result)) |
Output:
resultant array [[ 1 2 3 1] [45 4 7 2] [ 9 6 10 3]]
Method 5: Using np.column_stack()
Python3
import numpy as np ini_array = np.array([[ 1 , 2 , 3 ], [ 45 , 4 , 7 ], [ 9 , 6 , 10 ]]) # Array to be added as column column_to_be_added = np.array([ 1 , 2 , 3 ]) # Adding column to numpy array result = np.column_stack((ini_array, column_to_be_added)) # printing result print ( "resultant array" , str (result)) |
Output:
resultant array [[ 1 2 3 1] [45 4 7 2] [ 9 6 10 3]]
Python | Ways to add row/columns in numpy array
Given a Numpy array, the task is to add rows/columns basis on requirements to the Numpy array. Let’s see a few examples of this problem in Python.