python - 使用 NumPy 计算向量中的值

标签 python numpy vector scipy

我使用 NumPy。

我定义了一个向量 x使用 NumPy 和其他具有数值的变量。

我将返回一个向量 yx 长度相同但是值y[i]在这个向量中 y需要根据相应的x[i]由不同的公式计算.

我可以使用 NumPy 做一些聪明的事情还是我必须遍历向量 x以及 x 中的每个元素确定是否x[i]是大于还是小于特定值并确定对特定元素使用哪个公式?

我想我可以做类似的事情

y[x > a] = 2*x+7
y[x <= a] = 3*x+9
return y

最佳答案

查看 np.where http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html .

y = np.where(x > a, 2 * x + 7, 3 * x + 9)

关于python - 使用 NumPy 计算向量中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29879467/

相关文章:

Python:检查字符串是否符合特定格式

python - 在 numpy 数组中查找连续重复的 nan

python - 在numpy中将小矩阵与标量相乘的最有效方法

python - 如何将自定义函数应用于 xarray.DataArray.coarsen.reduce()?

c++ - 使用 vector 成员破坏对象

python - 难以使用脚本导入 GASP

python - 根据数据框中的现有时间列创建新列

python3 : Unescape unicode escapes surrounded by unescaped characters

postgresql - 如何使用 pgvector 修复 Postgres 错误 "operator does not exist"

Scala 使用可变条目填充或制表