簡體   English   中英

Python:帶有“ inf”的數組的最小值

[英]Python: Minimum value of an array with 'inf'

我從以下方面學到了inf的知識: 如何在Python中表示一個無限數?

我希望找到包含“ inf”的數組的最小值

In [330]: residuals
Out[330]: 
array([[ 2272.35651718,  1387.71126686,  1115.48728484],
       [  695.08009848,            inf,            inf],
       [  601.44997093,            inf,            inf]])

In [331]: min(residuals)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-331-69b09e4201cf> in <module>()
----> 1 min(residuals)

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

但是,似乎“ inf”是模棱兩可的嗎? 有一種聰明的方法來找到最小值,而不是對該數組的每個值運行循環嗎?

此問題與inf無關,它是將python的內置min函數與具有多個維度的numpy數組一起使用的副產品。

numpy.min( residuals )應該做您想要的 ,假設您正在尋找任何子數組中最小的元素。

嘗試-

residuals.min()

范例-

In [6]: import numpy as np

In [7]: a = np.array([[1,2,3,4],[np.inf,4,5,6],[7,8,9,10]])

In [8]: a
Out[8]:
array([[  1.,   2.,   3.,   4.],
       [ inf,   4.,   5.,   6.],
       [  7.,   8.,   9.,  10.]])

In [9]: a.min()
Out[9]: 1.0

您有一個矩陣,並且min不夠聰明,無法正確地進行迭代。 您可以使用numpy.min或類似的東西:

min([x for x in y for y in residuals])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM