2

I'm have a 585L, 2L numpy array in Python. The data is organized like in this example.

0,0
1,0
2,1
3,0
4,0
5,1
...

I would like to create an array deleting all the lines where 0 is present on the seconds column. Thus, the final result pretended is:

2,1
5,1

I have read some related examples but I'm still struggling with this.

1
  • How are you declaring the array? Commented Feb 20, 2015 at 11:07

3 Answers 3

1

Since you mention your structure being a numpy array, rather than a list, I would use numpy logical indexing to select only the values you care for.

>>> import numpy as np
>>> x = [[0,0], [1,0], [2,1], [3,0], [4,0], [5,1]] # Create dummy list
>>> x = np.asarray(x) # Convert list to numpy array
>>> x[x[:, 1] != 0] # Select out items whose second column don't contain zeroes

 array([[2, 1],
   [5, 1]])
Sign up to request clarification or add additional context in comments.

Comments

0

here is my answer if your list like this [[0,0],[2,1],[4,3],[2,0]] if your list structure isnt like this please tell me

my answer prints the list whose second column num dont equal to 0

    print [x for x in your_list if x[1] != 0] #your_list is the variable of the list 

1 Comment

Thank you also. Similar to @SimeonJM, I just replaced the != to ==
0

You could use an list comprehension. These are described on the Python Data Structures page (Python 2, Python 3).

If your array is:

x = [[0,0],
    [1,0],
    [2,1],
    [3,0],
    [4,0],
    [5,1]]

Then the following command

[y for y in x if y[1] != 0]

Would return the desired result of:

[[2, 1], [5, 1]]

Edit: I overlooked that it was a numpy array. Taking that into account, JoErNanO's answer is better.

3 Comments

Yes exactly what needed. I was trying to do something similar but my proposed array comprehension was messed up. Thanks.
Cool, glad it worked. JoErNanO's solution is more efficient for a numpy array, though, I believe.
Ok, in this cased I marked solved by @JoErNanO solution. Thank you both.

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.