[英]testing if a numpy array is symmetric?
Is there a better pythonic way of checking if a ndarray is diagonally symmetric in a particular dimension?是否有更好的 Pythonic 方法来检查 ndarray 在特定维度上是否对角对称? ie for all of x
即对于所有的 x
(arr[:,:,x].T==arr[:,:,x]).all()
I'm sure I'm missing an (duh) answer but its 2:15 here...:)我确定我错过了一个(duh)答案,但这里是 2:15 ...... :)
EDIT: to clarify, I'm looking for a more 'elegant' way to do:编辑:澄清一下,我正在寻找一种更“优雅”的方式来做:
for x in range(xmax):
assert (arr[:,:,x].T==arr[:,:,x]).all()
If I understand you correctly, you want to do the check 如果我理解正确,你想做检查
all((arr[:,:,x].T==arr[:,:,x]).all() for x in range(arr.shape[2]))
without the Python loop. 没有Python循环。 Here is how to do it:
这是怎么做的:
(arr.transpose(1, 0, 2) == arr).all()
If your array contains floats (especially if they're the result of a computation), use allclose
如果您的数组包含浮点数(特别是如果它们是计算的结果),请使用
allclose
np.allclose(arr.transpose(1, 0, 2), arr)
If some of your values might be NaN
, set those to a marker value before the test. 如果您的某些值可能是
NaN
,请在测试之前将其设置为标记值。
arr[np.isnan(arr)] = 0
I know you asked about NumPy.我知道你问过 Z3B7F949B2343F9E5390E29F6EF5E1778Z。 But SciPy, NumPy sister package, has a build-in function called
issymmetric
to check if a 2D NumPy array is symmetric. But SciPy, Z3B7F949B2343F9E5390E29F6EF5E1778Z sister package, has a build-in function called
issymmetric
to check if a 2D Z3B7F949B2343F9E5390E29F6EF5E1778Z array is symmetric. You can use it too.你也可以使用它。
>>> from scipy.linalg import issymmetric
>>> import numpy as np
>>> a = np.arange(27).reshape(3,3,3)
>>> a
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
>>> for i in range(a.shape[2]):
issymmetric(a[:,:,i])
False
False
False
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.