【问题标题】:Python, ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()Python,ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()
【发布时间】:2023-02-10 18:27:46
【问题描述】:

我的问题和我之前question的回答有关。

以前的解决方案中的代码和这个问题的当前代码之间的区别如下:在我的代码中,我必须设置函数“myfunc”返回两个不同的结果, if t==0: return(10) else: return np.sqrt(r**2 - t**2) 而不是只有一个回报: return np.sqrt(r**2 - t**2)

知道如果你运行文件它会引发 ValueError,

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

有人可以向我解释如何解决这个问题,而不更改函数以返回一个结果,因为我需要让它返回两个结果,这只是我遇到的问题的一个例子,我正在编写的程序与这个有很大不同.

太感谢了

from matplotlib import pyplot as plt
import numpy as np

# create the function (which you may not have access to)
def myfunc(t, r=1.0):
    if t==0:
        return (10)
    else:
        return np.sqrt(r**2 - t**2)

# generate some points at which the function has been evaluate
t = np.linspace(0, 1, 100)  # 100 points linearly spaced between 0 and 1
y = myfunc(t)  # the function evaluated at the points t

# assuming we just have t and y (and not myfunc), interpolate the value of
# the function at some point t1
t1 = 0.68354844
y1 = np.interp(t1, t, y)

# use piecewise to get a function which is constant below t1 and follows the
# original function above t1 (potentially evaluated at different points in t)
tnew = np.linspace(0, 1, 150)  # new (more highly sampled) points at which to evaluate the function

condlist = [tnew <= t1, tnew > t1]  # list of piecewise conditions
funclist = [y1, np.interp]  # use constant y1 for first condition and interp for second condition

# evaluate the piecewise function at tnew
yvals = np.piecewise(tnew, condlist, funclist, t, y)

# plot the original function and the new version with the constant section
fig, ax = plt.subplots()
ax.plot(t, y, label="Original function")
ax.plot(tnew, yvals, ls="--", label="Piecewise function")
ax.legend()

fig.show() 

我仍然是一般编程的初学者,所以请,如果你能写一个我容易理解的答案,那将非常有帮助,我真的很感激。

【问题讨论】:

  • t 将是一个值数组。如果t 包含 0,您是否希望 myfunc 仅返回单个值 10?或者您是否仍希望 myfunc 返回一个值数组,只是索引等同于 t 为零且包含值 10 的位置?

标签: python numpy matplotlib valueerror


【解决方案1】:

您只需将 t == 0 替换为 t.any() == 0 就像下面的代码:

if t == 0:
if t.any() == 0:

由于 tnumpy array,您必须检查 numpy 数组变量 t 中的所有值

【讨论】:

    【解决方案2】:

    t==0 是什么意思? t 是一个 numpy 数组(你将它定义为一个 linspace)。如果您指的是数组中的一个值,则需要对其进行迭代或使用 apply 方法

    y = np.array([myfunc(x) for x in t])

    【讨论】:

      最近更新 更多