Python 优化嵌套numpy阵列上的逻辑操作

Python 优化嵌套numpy阵列上的逻辑操作,python,optimization,numpy,Python,Optimization,Numpy,我从一个numpy数组开始,其中每个内部numpy数组可以有不同的长度。下面给出了一个例子: import numpy as np a = np.array([1,2,3]) b = np.array([4,5]) c = np.array([a, b]) print c [[1 2 3] [4 5]] 我希望能够对数组c中每个元素中的每个元素执行布尔运算,但当我尝试执行此操作时,我得到以下值错误: print c > 0 Traceback (most recent call las

我从一个numpy数组开始,其中每个内部numpy数组可以有不同的长度。下面给出了一个例子:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5])
c = np.array([a, b])

print c
[[1 2 3] [4 5]]
我希望能够对数组c中每个元素中的每个元素执行布尔运算,但当我尝试执行此操作时,我得到以下值错误:

print c > 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()

不使用for循环或在外部数组上迭代。这可能吗?如果可能的话,我该如何实现它?

我可以想出两种广泛的方法,要么填充数组,以便可以使用单个二维数组而不是嵌套数组,要么将嵌套数组视为数组列表。第一个看起来像这样:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5, -99])
c = np.array([a, b])

print c.shape
# (2, 3)
print c > 0
# [[ True  True  True]
#  [ True  True False]]
或者像这样做:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5])
c = np.array([a, b])

out = [i > 0 for i in c]
print out
# [array([ True,  True,  True], dtype=bool), array([ True,  True], dtype=bool)]

如果不选择填充,实际上您可能会发现数组列表的性能比数组数组的性能更好。

我可以想出两种广泛的方法,要么填充数组,以便可以使用单个二维数组而不是嵌套数组,要么将嵌套数组视为数组列表。第一个看起来像这样:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5, -99])
c = np.array([a, b])

print c.shape
# (2, 3)
print c > 0
# [[ True  True  True]
#  [ True  True False]]
或者像这样做:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5])
c = np.array([a, b])

out = [i > 0 for i in c]
print out
# [array([ True,  True,  True], dtype=bool), array([ True,  True], dtype=bool)]

如果不选择填充,实际上您可能会发现数组的列表比数组的数组表现得更好。

外部for循环有什么问题?Numpy擅长于具有固定维数的齐次数列。检查。外部for循环有什么问题?Numpy擅长于具有固定维数的齐次数列。检查。