Python | Ways to add rows / columns in a NumPy array



Method # 1: Using np.hstack()

# Python code for demo
# add columns to the numpy array

 

import numpy as np

  

ini_array = np.array ([[ 1 , 2 , 3 ], [ 45 , 4 , 7 ], [ 9 , 6 , 10 ]])

 
# print the original array

print ( "initial_array:" , str (ini_array)); 

 
# Array to be added as a column

column_to_be_added = np.array ([ 1 , 2 , 3 ])

 
# Add a column to the numpy array

result = np.hstack ((ini_array, np.atleast_2d (column_to_be_added) .T))

  
# print result

print ( "resultant array" , str (result))

Exit :

 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 the column_stack () method

# Python code to demonstrate
# add columns to the numpy array

 

import numpy as np

 

ini_array = np. array ([[ 1 , 2 , 3 ], [ 45 , 4 , 7 ], [ 9 , 6 , 10 ]])

 
# print the original array

print ( "initial_array:" , str (ini_array)); 

 
# Array to be added as a column

column_to_be_added = np.array ([ 1 , 2 , 3 ])

 
# Add a column to the numpy array

result = np.column_stack ((ini_array, column_to_be_added))

 
# print result

print ( "resultant array" , str (re sult))

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 # 3: Using np.vstack()

# Python code for demonstration
# adding lines to the numy array

 

import numpy as np

 

ini_array = np.array ([[ 1 , 2 , 3 ], [ 45 , < / code> 4 , 7 ], [ 9 , 6 , 10 ]])

 
# print the original array

print ( "initial_array:" , str (ini_array)); 

 
# Array to be added as a string

row_to_be_added = np.array ([ 1 , 2 , 3 ])

 
# Add line to numpy array

result = np.vstack ((ini_array, row_to_be_added))

 
# print result

print ( "resultant array" , str (result))

Exit:

 initial_array: [[1 2 3] [45 4 7] [9 6 10]] resultant array [[1 2 3] [45 4 7] [9 6 10] [1 2 3]]