1

What is the easiest way to save elements from a list using np.where or similar?

A short example:

l1 = [-144.92170726320364, 697.7739312692029, -2.0, -2.0]

I want to keep the elements which are different from -2.0. I tried:

l2 = [l1[index] for index in len(l1) if l1[index] != -2.0]

As well as:

l3 = np.where(l1 != -2.0)

In first case I received error. In the second case I obtained (array([0]),).

Thanks for the help.

3 Answers 3

3

If you change your list into a numpy.array

>>> import numpy as np
>>> l1 = np.array([-144.92170726320364, 697.7739312692029, -2.0, -2.0])

you can do the comparison against the scalar

>>> l1 != -2.0
array([ True,  True, False, False], dtype=bool)

Then use that expression to index into your original array

>>> l1[l1 != -2.0]
array([-144.92170726,  697.77393127])
Sign up to request clarification or add additional context in comments.

Comments

2

Normal Python array

l2 = [i for i in l1 if i!=-2.0]

Numpy array

l1 = np.array(l1)
l2 = l1[l1 != -2.0]

Comments

2

try this:

[l for l in l1 if l != -2.0]

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.