2

在 Python 的标准max函数中(我也可以传入一个关键参数):

s = numpy.array(['one','two','three'])
max(s) # 'two' (lexicographically last)
max(s, key=len) # 'three' (longest string)

使用更大的(多维)数组,我不能再使用max,所以我尝试使用numpy.amax,但是我似乎无法amax与字符串一起使用......

t = np.array([['one','two','three'],['four','five','six']])
t.dtype # dtype('|S5')
numpy.amax(t, axis=0) #Error! Hoping for: [`two`, `six`]

Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 1833, in amax
        return amax(axis, out)
TypeError: cannot perform reduce with flexible type

是否可以使用amax我使用不正确!),还是有其他numpy工具可以做到这一点?

4

1 回答 1

6

与其将字符串作为可变长度数据存储在numpy数组中,不如尝试将它们存储为 Python objects。Numpy 会将这些视为对原始 Python 字符串对象的引用,然后您可以像预期的那样对待它们:

t = np.array([['one','two','three'],['four','five','six']], dtype=object)
np.min(t)
# gives 'five'
np.max(t)
# gives 'two'

请记住,这里的np.minandnp.max调用按字典顺序对字符串进行排序——所以“二”确实出现在“五”之后。要更改比较运算符以查看每个字符串的长度,您可以尝试创建一个numpy形式相同的新数组,但包含每个字符串的长度而不是其引用。然后,您可以numpy.argmin对该数组进行调用(它返回最小值的索引)并在原始数组中查找字符串的值。


示例代码:

# Vectorize takes a Python function and converts it into a Numpy
# vector function that operates on arrays
np_len = np.vectorize(lambda x: len(x))

np_len(t)
# gives array([[3, 3, 5], [4, 4, 3]])

idx = np_len(t).argmin(0) # get the index along the 0th axis
# gives array([0, 0, 1])

result = t
for i in idx[1:]:
    result = result[i]
print result
# gives "two", the string with the smallest length
于 2012-09-29T15:48:27.437 回答