Python - ValueError:具有多个元素的数组的真值是不明确的。使用a.any()或所有()

时间:2022-09-05 16:07:48

I'm really new to programming, and I can't figure out how to use a Numpy array to be manipulated in a function such as P**2.

我是编程新手,我不知道如何使用Numpy数组在一个函数中操作,比如P* 2。

import math
import numpy
span_x = numpy.array([0,250,500,750,1000])
P = span_x
example = P**2
span_y = [example for i in P]
y = float(input("Enter y: "))
bracket1 = min(span_y, lambda span_y: abs(span_y-y))
if bracket1 < y:
    for i in span_y:
        bracket2 = span_y[span_y.index(bracket1) + 1]
else:
    for i in span_y:
        bracket2 = span_y[span_y.index(bracket1) - 1]
print "Brackets: ", bracket1, bracket2

I've tried not using a Numpy array, but received a TypeError.

我尝试过不使用Numpy数组,但是收到了一个类型错误。

My main issue is that I have this array of x-values (span_x) that I want to put into a function like P**2 and get y-values (span_y) in an array. Then, the user inputs a y-value and I want to check which y-value in span_y is closest to this input, and that is bracket1. bracket2 is the second closest y-value. I would love some help!

我的主要问题是我有一个x值数组(span_x)我想把它放到一个函数中,比如P* 2,然后在数组中得到y值(span_y)然后,用户输入一个y值,我要检查span_y中哪个y值最接近这个输入,那就是bracket1。bracket2是第二个最接近的y值。我想要一些帮助!

2 个解决方案

#1


1  

span_y is a list of 1D-arrays so min doesn't work as you expect and returns a function. After that span_y.index(bracket1) raises an exception. span_y should be initialized like this

span_y是一个一维数组的列表,因此min不能正常工作并返回一个函数。在那之后span .index(bracket1)引发了一个异常。应该像这样初始化span_y

span_y = list(example)

Pass your key function (lambda) in min as a named parameter as said in documention.

将键函数(lambda)作为一个命名参数传递给min,如文档中所述。

bracket1 = min(span_y, key = lambda span_y: abs(span_y-y))

#2


1  

In NumPy you can and should vectorize the operations like:

在NumPy中,您可以并且应该对操作进行矢量化:

span_y = span_x**2
y = float(input("Enter y: "))
bracket1 = np.array((span_y, np.abs(span_y - y))).min(axis=0)
bracket2 = np.zeros_like(bracket1)
bracket2[ bracket1 < y ] = np.roll(span_y, 1)
bracket2[ bracket1 >= y] = np.roll(span_y, -1)

#1


1  

span_y is a list of 1D-arrays so min doesn't work as you expect and returns a function. After that span_y.index(bracket1) raises an exception. span_y should be initialized like this

span_y是一个一维数组的列表,因此min不能正常工作并返回一个函数。在那之后span .index(bracket1)引发了一个异常。应该像这样初始化span_y

span_y = list(example)

Pass your key function (lambda) in min as a named parameter as said in documention.

将键函数(lambda)作为一个命名参数传递给min,如文档中所述。

bracket1 = min(span_y, key = lambda span_y: abs(span_y-y))

#2


1  

In NumPy you can and should vectorize the operations like:

在NumPy中,您可以并且应该对操作进行矢量化:

span_y = span_x**2
y = float(input("Enter y: "))
bracket1 = np.array((span_y, np.abs(span_y - y))).min(axis=0)
bracket2 = np.zeros_like(bracket1)
bracket2[ bracket1 < y ] = np.roll(span_y, 1)
bracket2[ bracket1 >= y] = np.roll(span_y, -1)