this question has answer here:
- numpy error in python 1 answer
what trying make table based on piece-wise function in python. example, wrote code:
import numpy np astropy.table import table, column astropy.io import ascii x = np.array([1, 2, 3, 4, 5]) y = x * 2 data = table([x, y], names = ['x', 'y']) ascii.write(data, "xytable.dat") xytable = ascii.read("xytable.dat") print xytable
this works expected, prints table has x
values 1 through 5 , y
values 2, 4, 6, 8, 10.
but, if instead want y
x * 2
if x
3 or less, , y
x + 2
otherwise?
if add:
if x > 3: y = x + 2
it says:
the truth value of array more 1 element ambiguous. use a.any() or a.all()
how code table works piece-wise function? how compare scalars numpy arrays?
you can possibly use numpy.where()
:
in [196]: y = np.where(x > 3, x + 2, y) in [197]: y out[197]: array([2, 4, 6, 6, 7])
the code above gets job done in vectorized manner. approach more efficient (and arguably more elegant) using list comprehensions , type conversions.
Comments
Post a Comment