Python:将数组元素与浮点值进行比较
我有一个数组Python:将数组元素与浮点值进行比较,python,arrays,numpy,logical-operators,Python,Arrays,Numpy,Logical Operators,我有一个数组A=[A0,A1],其中A0是4x3矩阵,A1是3x2矩阵。我想比较A和float,比如说,1.0,元素方面。预期的返回B=(A>1.0)是一个与A大小相同的数组。如何实现这一点 我可以将A复制到C,然后将C中的所有元素重置为1.0,然后进行比较,但我认为python(numpy/scipy)必须有一种更智能的方法来实现这一点。。。 谢谢 对1个矩阵使用列表理解 def compare(matrix,flo): return [[x>flo for x in y] f
A=[A0,A1]
,其中A0是4x3矩阵,A1是3x2矩阵
。我想比较A和float,比如说,1.0,元素方面。预期的返回B=(A>1.0)
是一个与A大小相同的数组。如何实现这一点
我可以将A复制到C,然后将C中的所有元素重置为1.0,然后进行比较,但我认为python(numpy/scipy)必须有一种更智能的方法来实现这一点。。。
谢谢 对1个矩阵使用列表理解
def compare(matrix,flo):
return [[x>flo for x in y] for y in matrix]
假设我正确理解了你的问题,例如
matrix= [[0,1],[2,3]]
print(compare(matrix,1.5))
应该打印[[False,False],[True,True]]
矩阵列表:
def compareList(listofmatrices,flo):
return [[[x>flo for x in y] for y in matrix] for matrix in listofmatrices]
或
更新:递归函数:
def compareList(listofmatrices,flo):
if(isinstance(listofmatrices, (int, float))):
return listofmatrices > flo
return [compareList(matrix,flo) for matrix in listofmatrices]
假设我们有与您提到的数组形状相同的数组:
>>> 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()
谢谢是的,3个for循环肯定会起作用。但我想知道python/numpy是否有一些内置功能来执行张量与标量元素的比较?我的意思是,如果以后我有一个秩100张量,例如,手工编制的代码将很麻烦(循环为100,当然不希望如此…@Void),你可以递归地这样做。你的
a
,具有对象的数据类型,只不过是一个数组列表。numpy的大部分功能是处理多维数字数组。一些操作,如基本数学操作,会“传递”到内部数组。我不知道是否有一个列表,列出哪些有效,哪些无效。
>>> 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=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)