Python – Numpy Array Column Deletion
Last Updated :
03 Apr, 2023
Given a numpy array, write a programme to delete columns from numpy array. Examples –
Input: [['akshat', 'nikhil'], ['manjeeet', 'akash']]
Output: [['akshat']['manjeeet']]
Input: [[1, 0, 0, 1, 0], [0, 1, 2, 1, 1]]
Output: [[1 0 1 0][0 2 1 1]]
Given below are various methods to delete columns from numpy array. Method #1: Using np.delete()
Python3
import numpy as np
ini_array = np.array([[ 1 , 0 , 0 , 1 , 0 ],
[ 0 , 1 , 2 , 1 , 1 ]])
result = np.delete(ini_array, 1 , 1 )
print ("Resultant Array :" + str (result))
|
Output:
Resultant Array :[[1 0 1 0]
[0 2 1 1]]
Time Complexity: O(n)
Space Complexity: O(n)
where n is length of array
Method #2: Using compress() and logical_not()
Python3
import numpy as np
ini_array = np.array([[ 1 , 0 , 0 , 1 , 0 ], [ 1 , 2 , 0 , 0 , 1 ]])
z = [ False , True , False , False , False ]
result = ini_array.compress(np.logical_not(z), axis = 1 )
print ("Resultant Array :" + str (result))
|
Output:
Resultant Array :[[1 0 1 0]
[1 0 0 1]]
Time Complexity: O(n)
Space Complexity: O(n)
where n is length of array
Method #3: Using logical_not()
Python3
import numpy as np
ini_array = np.array([[ 1 , 0 , 0 , 1 , 0 ], [ 1 , 2 , 0 , 0 , 1 ]])
z = [ False , True , False , False , False ]
result = ini_array[:, np.logical_not(z)]
print ("Resultant Array :" + str (result))
|
Output:
Resultant Array :[[1 0 1 0]
[1 0 0 1]]
Time Complexity: O(n)
Space Complexity: O(n)
where n is length of array
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...