Numpy 布尔语句 - 在语句中使用 a.any() 和 a.all() 的帮助

所以假设我有一个变量 a 它是一个 numpy 数组。当 a 小于某个值时,我想应用某个函数,而当它大于这个值时,我将应用一个不同的函数。


我尝试使用布尔 if 语句执行此操作,但返回以下错误:


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

我从这个答案中知道我需要使用 numpy a.any() 和 a.all() 但我不清楚在循环中如何/在哪里使用它们。我在下面提供了一个非常简单的示例:


import numpy as np


a = np.linspace(1, 10, num=9)


def sortfoo(a):

    if a < 5:

        b = a*3

    else:

        b = a/2

    return b


result = sortfoo(a)

print(result)

所以我想我是在问一个例子,说明我需要在哪里以及如何在上面使用 any() 和 all() 。


非常基本的问题,但由于某种原因,我的大脑工作不清晰。非常感谢任何帮助。


UYOU
浏览 508回答 2
2回答

BIG阳

鉴于描述,这看起来像一个用例np.where()a = np.linspace(1, 10, num=9)b = np.where(a<5,a*3,a/2)barray([ 3.&nbsp; &nbsp; ,&nbsp; 6.375 ,&nbsp; 9.75&nbsp; , 13.125 ,&nbsp; 2.75&nbsp; ,&nbsp; 3.3125,&nbsp; 3.875 ,&nbsp; &nbsp; 4.4375,&nbsp; 5.&nbsp; &nbsp; ])由于您还提到想要应用不同的功能,您可以使用相同的语法def f1(n):&nbsp; &nbsp; return n*3def f2(n):&nbsp; &nbsp; return n/2np.where(a<5,f1(a),f2(a))array([ 3.&nbsp; &nbsp; ,&nbsp; 6.375 ,&nbsp; 9.75&nbsp; , 13.125 ,&nbsp; 2.75&nbsp; ,&nbsp; 3.3125,&nbsp; 3.875 ,&nbsp; &nbsp; &nbsp; &nbsp; 4.4375,&nbsp; 5.&nbsp; &nbsp; ])

慕桂英546537

在 numpy 中使用简单的语句,您可以这样做:import numpy as npa = np.linspace(1, 10, num=9)s = a < 5 # Test a < 5a[s] = a[s] * 3a[s == False] = a[s == False] / 2
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python