Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy equivalent of if/else list comprehension

Tags:

python

numpy

Is there a numpy way of doing

n = [x-t if x > 0 else x for x in nps]

similar to this

n = np.array(a)
n[np.abs(n) < t] = 0

something like this perhaps?

n[n > 0] = n-t
like image 578
kasperhj Avatar asked Oct 18 '13 20:10

kasperhj


People also ask

Can you do List Comprehension with Numpy?

You can even even use Pandas Series or Numpy Arrays with List Comprehension.

Can I use if else in List Comprehension python?

b. if..else in List Comprehension in Python. You can also use an if-else in a list comprehension in Python. Since in a comprehension, the first thing we specify is the value to put in a list, this is where we put our if-else.

Is List Comprehension faster than Numpy?

List comprehensions on tiny lists are faster than doing the same with numpy as the performance gain from using numpy is not enough to offset the overhead of creating an array.

Can you use a list in an if statement Python?

Answer. Yes, an else clause can be used with an if in a list comprehension. The following code example shows the use of an else in a simple list comprehension.


1 Answers

Can't test now, but try

np.where(n > 0, n - t, n)

See documentation

like image 175
Roman Pekar Avatar answered Oct 10 '22 14:10

Roman Pekar