Filter array by value in last column

Question:

I have matrix like this:

m1 = 
[1, 3, 4, 2, 1, 1]
[1, 3, 5, 3, 3, 1]
[1, 2, 3, 1, 1, 0]
[1, 3, 7, 3, 1, 1]

I need to filter it tp get value 1 in the last column. So result should be like this:

filter_array = 
[1, 3, 4, 2, 1, 1]
[1, 3, 5, 3, 3, 1]
[1, 3, 7, 3, 1, 1]

My current code is:

m1 = np.array  ##see array above
filter_array = [ ]  ## the filtered array will be stored here. raw by raw 
for raw in m1: 
    if raw[-1] ==1:
        filter_array = filter_array.append(raw[:])

My code gives me back an empty array. I’ve must missed something…

Asked By: Ali

||

Answers:

Simply do this:

filtered = m1[m1[:, -1] == 1]

Note: Your original code did not work because you were assigning the return value of append() method to the filter_array. Since the return value when append to a list is successful is None, you lose your original list after reassigning it to None.
To get your code working, simply do filter_array.append(row[:]) as this mutates the list in place. Simply appending row also works.

Answered By: swag2198

filter_array.append(raw[:]) returns nothing. Its NoneType.
So you cannot append row to a NoneType object the second time it executes in the loop.

Your corrected loop should be:

filter_array = []
for raw in m1: 
    if raw[-1] ==1:
        filter_array.append(raw[:])
print(filter_array)

Or better you could use list comprehension and boolean indexing like below:

 filter_array = m1[[True if arr[-1] == 1 else False for arr in m1]]
Answered By: SomeDude
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.