Skip to main content
 首页 » 编程设计

python之将函数应用于 numpy 列表数组中的每个列表

2025年05月04日15jirigala

我有一个接受列表(字符串)的函数。它对该列表进行一些处理并返回另一个字符串列表,长度可能更短。

现在,我有一个字符串输入列表的 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 

请您参考如下方法:

从 vectorize 的文档字符串中,它读取了关于可选参数 otypes

otypes : str or list of dtypes, optional 
    The output data type. It must be specified as either a string of 
    typecode characters or a list of data type specifiers. There should 
    be one data type specifier for each output. 

它允许您创建具有复杂输出的结构化数组,但也解决了您将列表作为数组元素的问题。

my_func_vec = np.vectorize(my_func, otypes=[list])