假设我们有你提到的数组的相同形状:
>>> A=np.array([np.random.random((4,3)), np.random.random((3,2))])
>>> A
array([ array([[ 0.20621572, 0.83799579, 0.11064094],
[ 0.43473089, 0.68767982, 0.36339786],
[ 0.91399729, 0.1408565 , 0.76830952],
[ 0.17096626, 0.49473758, 0.158627 ]]),
array([[ 0.95823229, 0.75178047],
[ 0.25873872, 0.67465796],
[ 0.83685788, 0.21377079]])], dtype=object)
我们可以用 where 子句测试每个元素:
>>> A[0]>.2
array([[ True, True, False],
[ True, True, True],
[ True, False, True],
[False, True, False]], dtype=bool)
但不是全部:
>>> A>.2
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()
因此,只需重建数组 B:
>>> B=np.array([a>.2 for a in A])
>>> B
array([ array([[ True, True, False],
[ True, True, True],
[ True, False, True],
[False, True, False]], dtype=bool),
array([[ True, True],
[ True, True],
[ True, True]], dtype=bool)], dtype=object)