1

I have a MATLAB code that looks like this:

dindex =find(H2(:,1)>=2400)
H2     =H2(dindex,:);

I find all the rows of a 2-d array, H2, in which its 1st column is bigger than 2400.

How can this be done in Python?

1 Answer 1

1

I would recommend using numpy for this, it's a very powerful python library that makes this sort of task trivial.

numpy.where() is what you are looking for here:

>>> import numpy as np
>>> arr = np.array([[2500, 1, 1, 1, 1], [2300, 1, 1, 1, 1], [2600, 1, 1, 1, 1]])
>>> arr
array([[2500,    1,    1,    1,    1],
       [2300,    1,    1,    1,    1],
       [2600,    1,    1,    1,    1]])
>>> np.where(arr[:,0] >= 2400)
(array([0, 2], dtype=int64),)

If you only want to keep the rows that meet this condition, you can do this with numpy indexing:

>>> arr = np.array([[2500, 1, 1, 1, 1], [2300, 1, 1, 1, 1], [2600, 1, 1, 1, 1]])
>>> arr
array([[2500,    1,    1,    1,    1],
       [2300,    1,    1,    1,    1],
       [2600,    1,    1,    1,    1]])
>>> arr = arr[np.where(arr[:,0] >= 2400)]
>>> arr
array([[2500,    1,    1,    1,    1],
       [2600,    1,    1,    1,    1]])
Sign up to request clarification or add additional context in comments.

2 Comments

i've never used numpy before, so i am a bit confused. I want to replace the original 2-d array with only rows with its 1st column bigger than 2400. How can I do that, after your code? So, in the list 'arr', I want to remove the middle row, by using the index obtained from numpy.
Updated my answer.

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.