【问题标题】:Optimizing logical operations on nested numpy arrays优化嵌套 numpy 数组的逻辑操作
【发布时间】:2013-06-05 15:02:41
【问题描述】:

我从 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 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()

我希望能够得到结果:

[[True True True] [True True]]

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

【问题讨论】:

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

标签: python optimization numpy


【解决方案1】:

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

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)]

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2015-10-27
    • 1970-01-01
    • 2022-07-29
    • 2020-12-09
    • 1970-01-01
    • 2020-01-08
    相关资源
    最近更新 更多