Tampa
Tampa

Reputation: 78254

Python and numpy - removing rows from a corresponding matrix

I am using numpy.

I have one array Y and one matrix X. This is for a regression. They arrays has labels, e.g. 0,1,2,3,4,5. I need to create a new array that has label 0 removed for all rows and the corresponding row in X removed as well. What is the most efficient means to do this?

e.g.

for i in xrange(y.shape):
    if y==0:
       pop y pop X

Upvotes: 0

Views: 425

Answers (2)

ntk4
ntk4

Reputation: 1307

If you know that you will always have that empty row no matter what, I don't see why you even need NUMPY to do this...

Z = Z[:][1:]

If it's just the first row this will actually work for the matrix, and of course the array

Z = Z[1:]

I like @eumiro's solution if you don't care about the placement of the items in the matrix, but their solution will remove all zeros and shift elements I believe.

Upvotes: 0

eumiro
eumiro

Reputation: 212885

Numpy arrays are not good at appending/removing rows. If you know which rows are to be deleted, just extract the other rows (you need) and create a new array.

I don't understand your question very well, so please correct me if I am wrong:

x = x[y != 0]
y = y[y != 0]

Example:

import numpy as np
x = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]])
y = np.array([1, 0, 3])
x = x[y != 0]
y = y[y != 0]

now:

x == array([[11, 12, 13],
            [31, 32, 33]])
y == array([1, 3])

Upvotes: 3

Related Questions