在 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
工具可以做到这一点?
最佳答案
与其将字符串作为可变长度数据存储在 numpy
数组中,不如尝试将它们存储为 Python object
。 Numpy 会将这些视为对原始 Python 字符串对象的引用,然后您可以像您期望的那样对待它们:
t = np.array([['one','two','three'],['four','five','six']], dtype=object)
np.min(t)
# gives 'five'
np.max(t)
# gives 'two'
请记住,此处 np.min
和 np.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
关于python - 字符串数组到 numpy.amax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12654093/