我有一个函数,我想将其应用于元组数组,我想知道是否有一种干净的方法可以做到这一点。
通常,我可以使用 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]]])
因此,与其对您的函数进行矢量化,因为它基本上会通过数组的元素(整数)进行循环,您应该 apply it on the suitable axis (“元组”的轴)而不关心序列的类型:
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])
