NickBraunagel
NickBraunagel

Reputation: 1599

Reshape numpy array

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.

Upvotes: 1

Views: 267

Answers (4)

Achyuta nanda sahoo
Achyuta nanda sahoo

Reputation: 455

you need to do slice op.

y = x[:,:2]

Upvotes: 1

ksai
ksai

Reputation: 977

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

Upvotes: 3

Steve Geluso
Steve Geluso

Reputation: 159

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]]

Upvotes: 1

JohanL
JohanL

Reputation: 6891

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.

Upvotes: 2

Related Questions