Numpy: .max() 和 .min() 不适用于 'S' 和 'U' 类型的数组(Trac #1316)

创建于 2012-10-19  ·  4评论  ·  资料来源: numpy/numpy

_原票http://projects.scipy.org/numpy/ticket/1316 on 2009-12-07 by @mdboom ,分配给

这是一个明智的操作。 如果可能的话,让它工作会很好。

In [25]: x.max()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/wonkabar/data1/builds/betadrizzle/<ipython console> in <module>()

TypeError: cannot perform reduce with flexible type

In [26]: x.min()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/wonkabar/data1/builds/betadrizzle/<ipython console> in <module>()

TypeError: cannot perform reduce with flexible type

In [27]:
00 - Bug Other

所有4条评论

这应该是可行的。 请注意, argmaxargmin工作,并且可能提供简单的方法来实现这一点,而无需使用maximum.reduce

.max可以接受一个轴元组, argmax只能处理一个axis ,所以要让它在一般情况下工作需要大量的轴洗牌,并可能复制以合并这些轴。 keepdimsout也在max的签名中,但不在argmax的签名中。 会涉及哪些类型? “S”、“U”和“V”?

这是否与 nr.conf 中描述的问题相同

In [1]: np.array([['dd', 'de', 'cc'], ['ae', 'be', 'hf']]).max(axis=0)
TypeError: cannot perform reduce with flexible type

对于@jondo的问题(此时是近 4 年前,但值得解决),是的。

费尔德曼博士的抱怨最好用一个例子来表达。 他说:“因为 NumPy 的 .min() 和 .max() 方法适用于数字数组,而 Python 的 min() 和 max() 函数适用于字符串,人们可能合理地期望 NumPy 的 .min() 和 .max() 方法适用于字符串数组,但它们不[...]”

这是一个插图:

import numpy as np

arr_str = np.array(["I'm", "Defying", "Gravity"]) #A wickedly simple array of strings

print(arr_str.max()) #raises "TypeError: cannot perform reduce with flexible type"
#Interestingly, when I just used a native Python list, the error for this line was: "AttributeError: 'list' object has no attribute 'max'"

print(max(arr_str)) #does not raise any kind of error and returns "I'm" no matter where it is in the array of strings above

#This code works as expected
arr_num = np.array([1,2,3,-1])
print(max(arr_num))

正如 Feldman 博士所说,他的问题是关于字符串数组并希望使用 .max() 而不是 max(); 但我们可以将其扩展到对任何灵活类型的关注。 请注意,他没有提到当我们将数组作为参数传入时 max() 工作得很好,但是正如您从上面的示例中看到的那样,它确实有效。

我验证了@charris所说的 .argmax() 确实有效。

我对社区的问题是:这是否足以成为一个问题(必须使用 max(list) 或 list.argmax),值得深入研究@jaimefrio提出的轴问题吗?

此页面是否有帮助?
0 / 5 - 0 等级