1

I have a numpy array X of shape (20000,3):

X = array([[  3,   8,   4],
           [  1,   2,   4],
           ...
           [  5,   8,   4],
           [  3,   9,   4]])

I want to drop the last 'column' (i.e. where the 4s are located), to get something like this:

X = array([[  3,   8],
           [  1,   2],
           ...
           [  5,   8],
           [  3,   9]])

Do I need to use a list comprehension to do this (i.e. iterate over array elements, save results to a list and convert list to array, or can I use a built-in numpy function, such as extract or where? Maybe you recommend something all together different? Thank you.

1
  • 1
    You can try this : y = X[:, :2] Commented Jul 10, 2017 at 6:18

4 Answers 4

3

Use scipy or numpy, specify the array, column_to_delete, row/column

scipy.delete(X, 2, 1)   #(np.array, index, axis)
numpy.delete(X, 2, 1) # would give the same result
Sign up to request clarification or add additional context in comments.

Comments

2

All you need to do is to pick out a slice of the original array:

X = np.array([[  3,   8,   4],
              [  1,   2,   4],
              [  5,   8,   4],
              [  3,   9,   4]])

newX = np.array(X[:,:-1])

Here I have chosen all rows and all but the last column of the original array. Then, in addition I have made it to a new array (the extra np.array() wrapping) in order to ensure it gets new memory. Otherwise it will just be a view of the original array and any updates to newX will also affect X.

2 Comments

why np.array for slicing X?
@Shai To ensure a new array and thereby new memory layout. It is not strictly necessary, but as I wrote in the answer, it prevents updates to the new array not affect the original one.
1
import numpy
X = numpy.array([[  3,   8,   4],
           [  1,   2,   4],
           [  5,   8,   4],
           [  3,   9,   4]])
XX = X[:,:-1]
print(XX)

# [[3 8]
#  [1 2]
#  [5 8]
#  [3 9]]

Comments

1

you need to do slice op.

y = x[:,:2]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.