我有一个接受列表(字符串)的函数。它在该列表上进行一些处理并返回另一个字符串列表,可能长度较短。将函数应用于列表的numpy数组中的每个列表
现在,我有一个numpy的字符串输入列表数组。我想将这个转换函数应用到我的数组中的每个列表。
从我迄今为止进行的搜索中,看起来好像vectorize或apply_along_axis可能是很好的候选人,但都没有像预期的那样工作。
我想尽可能有效地做到这一点。最终输入数组将包含大约100K个列表。
我想我可以遍历for
循环中的numpy数组,然后将append
每个输出列表一次一个迭代到一个新的输出数组中,但这看起来非常低效。
这是我试过的。出于测试目的,我做了一个虚拟转换函数,输入数组只包含3个列表。
def my_func(l):
# accepts list, returns another list
# dumbed down list transformation function
# for testing, just return the first 2 elems of original list
return l[0:2]
test_arr = np.array([['the', 'quick', 'brown', 'fox'], ['lorem', 'ipsum'], ['this', 'is', 'a', 'test']])
np.apply_along_axis(my_func, 0, test_arr)
Out[51]: array([['the', 'quick', 'brown', 'fox'], ['lorem', 'ipsum']], dtype=object)
# Rather than applying item by item, this returns the first 2 elements of the entire outer array!!
# Expected:
# array([['the', 'quick'], ['lorem', 'ipsum'], ['this', 'is']])
# Attempt 2...
my_func_vec = np.vectorize(my_func)
my_func_vec(test_arr)
结果:
Traceback (most recent call last):
File "<ipython-input-56-f9bbacee645c>", line 1, in <module>
my_func_vec(test_arr)
File "C:\Users\Tony\Anaconda2\lib\site-packages\numpy\lib\function_base.py", line 2218, in __call__
return self._vectorize_call(func=func, args=vargs)
File "C:\Users\Tony\Anaconda2\lib\site-packages\numpy\lib\function_base.py", line 2291, in _vectorize_call
copy=False, subok=True, dtype=otypes[0])
ValueError: cannot set an array element with a sequence
这已被讨论过很多次。无论是矢量化还是应用...'会提高'效率'。他们仍然需要在每个列表上调用您的函数,并将结果累加到数组或列表中。总的来说,它运行你的函数100k次将会很慢,而不是迭代框架。 – hpaulj
在过去的测试中,我发现'np.frompyfunc'是迭代对象数组的好工具。 – hpaulj
其实我想的完全一样,但决定回答这个问题,而不是告诉我该怎么做。但后来我测试了它,出于某种原因,矢量化比列表理解或map()函数快10倍...任何想法为什么? – dnalow