dudas
dudas

Reputation: 423

Delete line from 2D array in Python

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.

Upvotes: 2

Views: 3126

Answers (3)

SimeonJM
SimeonJM

Reputation: 667

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.

Upvotes: 0

JoErNanO
JoErNanO

Reputation: 2488

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

Upvotes: 1

Mohamed Ramzy Helmy
Mohamed Ramzy Helmy

Reputation: 269

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 

Upvotes: 0

Related Questions