25

I want to remove rows from a two dimensional numpy array using a condition on the values of the first row.

I am able to do this with regular python using two loops, but I would like to do it more efficiently with numpy, e.g. with numpy.where

I have been trying various things with numpy.where and numpy.delete but I struggle with applying a condition to the first column only.

Here is an example where I only want to keep the rows where the first value of each row is 6.

Input:

[[0,4],
 [0,5],
 [3,5],
 [6,8],
 [9,1],
 [6,1]]

Output:

[[6,8],
 [6,1]]
2
  • 5
    You just need to use 2D indexing. arr = arr[arr[:,0] == 6] Commented Sep 24, 2019 at 11:23
  • Thanks, that is even short than using numpy.where Commented Sep 24, 2019 at 11:32

2 Answers 2

32

Use a boolean mask:

mask = (z[:, 0] == 6)
z[mask, :]

This is much more efficient than np.where because you can use the boolean mask directly, without having the overhead of converting it to an array of indices first.

One liner:

z[z[:, 0] == 6, :]
Sign up to request clarification or add additional context in comments.

1 Comment

We can make it even more simple one liner, as without ":" it means just the row: z=z[z[:,0]==6]
7

Program:

import numpy as np
np_array = np.array([[0,4],[0,5],[3,5],[6,8],[9,1],[6,1]])
rows=np.where(np_array[:,0]==6)
print(np_array[rows])

Output:

[[6 8]
 [6 1]]

And If You Want to Get Into 2d List use

np_array[rows].tolist()

Output of 2d List

[[6, 8], [6, 1]]

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.