Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove a specific column in numpy

Tags:

>>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) >>> arr array([[ 1,  2,  3,  4],        [ 5,  6,  7,  8],        [ 9, 10, 11, 12]]) 

I am deleting the 3rd column as

>>> np.hstack(((np.delete(arr, np.s_[2:], 1)),(np.delete(arr, np.s_[:3],1)))) array([[ 1,  2,  4],        [ 5,  6,  8],        [ 9, 10, 12]]) 

Are there any better way ? Please consider this to be a novice question.

like image 434
user644745 Avatar asked May 19 '13 08:05

user644745


People also ask

How do I remove an element from a NumPy array?

To remove an element from a NumPy array: Specify the index of the element to remove. Call the numpy. delete() function on the array for the given index.

How do you delete a column from a 2D array in Python?

Delete a column in 2D Numpy Array by column number To delete a column from a 2D numpy array using np. delete() we need to pass the axis=1 along with numpy array and index of column i.e.

How does NP delete work?

The numpy. delete() function returns a new array with the deletion of sub-arrays along with the mentioned axis. Return : An array with sub-array being deleted as per the mentioned object along a given axis.

How do I delete multiple rows in NumPy?

delete() – The numpy. delete() is a function in Python which returns a new array with the deletion of sub-arrays along with the mentioned axis. By keeping the value of the axis as zero, there are two possible ways to delete multiple rows using numphy. delete().


2 Answers

If you ever want to delete more than one columns, you just pass indices of columns you want deleted as a list, like this:

>>> a = np.arange(12).reshape(3,4) >>> a array([[ 0,  1,  2,  3],        [ 4,  5,  6,  7],        [ 8,  9, 10, 11]]) >>> np.delete(a, [1,3], axis=1) array([[ 0,  2],        [ 4,  6],        [ 8, 10]]) 
like image 166
Akavall Avatar answered Oct 27 '22 12:10

Akavall


>>> import numpy as np >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) >>> np.delete(arr, 2, axis=1) array([[ 1,  2,  4],        [ 5,  6,  8],        [ 9, 10, 12]]) 
like image 35
jamylak Avatar answered Oct 27 '22 10:10

jamylak