python numpy set elements of list by condition
Question:
I want to set a specific element of my list to specific value with low overhead.
for example if I have this : a = numpy.array([1,2,3,0,4,0])
I want to change every 0 value to 10; in the end I want to have [1, 2, 3, 10, 4, 10]
in Matlab you can do this easily like a(a==0) = 10, is there any equivalent in numpy?
Answers:
Remarkably similar to Matlab:
>>> a[a == 0] = 10
>>> a
array([ 1, 2, 3, 10, 4, 10])
There’s a really nice "NumPy for Matlab Users" guide at the SciPy website.
I should note, this doesn’t work on regular Python lists. NumPy arrays are a different datatype that work a lot more like a Matlab matrix than a Python list in terms of access and math operators.
A little more pythonic way would be like this, I guess:
import numpy
a = numpy.array([1,2,3,0,4,0])
for k,v in enumerate(a):
if v == 0:
a[k] = 10
print a
Even more pythonic way (provided by @mtrw)
[10 if k == 0 else k for k in a]
I want to set a specific element of my list to specific value with low overhead.
for example if I have this : a = numpy.array([1,2,3,0,4,0])
I want to change every 0 value to 10; in the end I want to have [1, 2, 3, 10, 4, 10]
in Matlab you can do this easily like a(a==0) = 10, is there any equivalent in numpy?
Remarkably similar to Matlab:
>>> a[a == 0] = 10
>>> a
array([ 1, 2, 3, 10, 4, 10])
There’s a really nice "NumPy for Matlab Users" guide at the SciPy website.
I should note, this doesn’t work on regular Python lists. NumPy arrays are a different datatype that work a lot more like a Matlab matrix than a Python list in terms of access and math operators.
A little more pythonic way would be like this, I guess:
import numpy
a = numpy.array([1,2,3,0,4,0])
for k,v in enumerate(a):
if v == 0:
a[k] = 10
print a
Even more pythonic way (provided by @mtrw)
[10 if k == 0 else k for k in a]