2

I have a 2 dimensional numpy array:

a=np.array([[1,2,3], 
            [4,5,6,7], 
            [2,3,4]])

How can i efficiently remove the element(row), which contains more than 3 elements(columns), without knowledge about its position?

    a=np.array([[1,2,3], 
                [2,3,4]])

"Remove all rows which are longer than 3."

3
  • You don't have a 2D numpy array; they can't vary row lengths like that. You probably have a 1D numpy array with dtype=object. Commented Jul 9, 2014 at 14:37
  • thx, but it seems to work ok, so the index to adress elements is kind of the same as in a 2d numpy array? Commented Jul 9, 2014 at 14:43
  • If you don't need to do any vector ops, or do any vector slicing. Try a * 2, for example, or a[:,1]. Commented Jul 9, 2014 at 14:44

1 Answer 1

4

This should do the trick (assuming the array is in variable a):

np.array([row for row in a if len(row)<=3])

I use a list comprehension on the numpy array a and only select the elements whose length is three or smaller.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.