我有一个函数想应用于数组元组,我想知道是否有一种干净的方法可以做到这一点。
通常,我可以np.vectorize
将函数应用于数组中的每个项目,但是,在这种情况下,“每个项目”是一个元组,因此numpy将数组解释为3d数组,并将函数应用于元组中的每个项目。
因此,我可以假设传入数组是以下之一:
我可能可以编写一些循环逻辑,但似乎numpy
最有可能具有更有效地执行此操作的功能,并且我不想重蹈覆辙。
这是一个例子。我试图将tuple_converter
函数应用于数组中的每个元组。
array_of_tuples1 = np.array([
[(1,2,3),(2,3,4),(5,6,7)],
[(7,2,3),(2,6,4),(5,6,6)],
[(8,2,3),(2,5,4),(7,6,7)],
])
array_of_tuples2 = np.array([
(1,2,3),(2,3,4),(5,6,7),
])
plain_tuple = (1,2,3)
# Convert each set of tuples
def tuple_converter(tup):
return tup[0]**2 + tup[1] + tup[2]
# Vectorizing applies the formula to each integer rather than each tuple
tuple_converter_vectorized = np.vectorize(tuple_converter)
print(tuple_converter_vectorized(array_of_tuples1))
print(tuple_converter_vectorized(array_of_tuples2))
print(tuple_converter_vectorized(plain_tuple))
所需的输出array_of_tuples1
:
[[ 6 11 38]
[54 14 37]
[69 13 62]]
所需的输出array_of_tuples2
:
[ 6 11 38]
所需的输出plain_tuple
:
6
但是上面的代码会产生此错误(因为它试图将函数应用于整数而不是元组。)
<ipython-input-209-fdf78c6f4b13> in tuple_converter(tup)
10
11 def tuple_converter(tup):
---> 12 return tup[0]**2 + tup[1] + tup[2]
13
14
IndexError: invalid index to scalar variable.
array_of_tuples1和array_of_tuples2实际上不是元组数组,而只是3维和2维整数数组:
In [1]: array_of_tuples1 = np.array([
...: [(1,2,3),(2,3,4),(5,6,7)],
...: [(7,2,3),(2,6,4),(5,6,6)],
...: [(8,2,3),(2,5,4),(7,6,7)],
...: ])
In [2]: array_of_tuples1
Out[2]:
array([[[1, 2, 3],
[2, 3, 4],
[5, 6, 7]],
[[7, 2, 3],
[2, 6, 4],
[5, 6, 6]],
[[8, 2, 3],
[2, 5, 4],
[7, 6, 7]]])
因此,与其对向量进行矢量化处理,不如对其进行向量化处理,因为它基本上将遍历数组的各个元素(整数),而应将其应用于合适的轴(“元组”的轴),而不用关心函数的类型。序列:
In [6]: np.apply_along_axis(tuple_converter, 2, array_of_tuples1)
Out[6]:
array([[ 6, 11, 38],
[54, 14, 37],
[69, 13, 62]])
In [9]: np.apply_along_axis(tuple_converter, 1, array_of_tuples2)
Out[9]: array([ 6, 11, 38])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句