比较标量和 Numpy 数组

Comparing scalars to Numpy arrays

我想做的是根据 Python 中的分段函数制作一个 table。例如,假设我写了这段代码:

import numpy as np
from astropy.table import Table, Column
from 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

这按预期工作,它打印 table 具有 x 值 1 到 5 和 y 值 2、4、6、8、10。

但是,如果我希望 y 仅在 x 等于或小于 3 时才为 x * 2,否则 yx + 2 怎么办? ?

如果我添加:

if x > 3: 
    y = x + 2

它说:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如何编写 table 代码,使其作为分段函数运行?我如何比较标量和 Numpy 数组?

开始不要使用 numpy(或者也许你可以,我不知道 numpy),只使用常规 python 列表。

x = [ 1, 2, 3, 4, 5 ]
y = [ i * 2 if i < 3 else i + 2 for i in x ]
print y

输出:

[2, 4, 5, 6, 7]

然后你可以把它变成一个numpy数组:

x = np.array(x)
y = np.array(y)

您可以使用 numpy.where():

In [196]: y = np.where(x > 3, x + 2, y)

In [197]: y
Out[197]: array([2, 4, 6, 6, 7])

上面的代码以完全矢量化的方式完成了工作。这种方法通常比使用列表理解和类型转换更有效(并且可以说更优雅)。