[英]Checking if a numpy array has the same number of elements across its length and width
Given a numpy array, what is the best way to check if it has the same number of elements across its length and width?给定一个 numpy 数组,检查它的长度和宽度是否具有相同数量的元素的最佳方法是什么? So for example, in the following arrays,
例如,在以下数组中,
arr1 = np.array([[0,1],[2,3],[4,5]])
arr2 = np.array([1,2,None,4])
arr3 = np.array([1,2,3,[4,5]])
arr1
, arr2
are OK but arr3
is not OK. arr1
, arr2
可以,但arr3
不行。
This SO post partially answers my question but it doesn't quite work because it will say arr2
is not OK because it has None
. 这篇 SO 帖子部分回答了我的问题,但它并不完全有效,因为它会说
arr2
不好,因为它有None
。
here is a piece of code cleverly using try-except to check the required conditions.这是一段巧妙地使用 try-except 来检查所需条件的代码。 (This should cover all cases of numerical data).
(这应该涵盖所有数值数据的情况)。
.astype(float)
is able to handle None and it converts it to nan. .astype(float)
能够处理 None 并将其转换为 nan。 list
is not handled by it, so we can use that to differentiate. list
不由它处理,所以我们可以用它来区分。
def check_arr(array):
try:
array = array.astype(float)
return "OK"
except:
return "not OK"
arr1 = np.array([[0,1],[2,3],[4,5]])
arr2 = np.array([1,2,None,4])
arr3 = np.array([1,2,3,[4,5]])
print(f"arr1 is {check_arr(arr1)}")
print(f"arr2 is {check_arr(arr2)}")
print(f"arr3 is {check_arr(arr3)}")
Output:输出:
arr1 is OK
arr2 is OK
arr3 is not OK
A better way would be to do this:更好的方法是这样做:
def check_arr(array):
return "not OK" if array.dtype==object else "OK"
but this won't work in your case as a valid case in your example has the NoneType value, which makes the array datatype object
.但这在您的情况下不起作用,因为您的示例中的有效情况具有 NoneType 值,这使得数组数据类型
object
。 I would suggest you use np.nan
and float arrays instead of None
in general for such cases.对于这种情况,我建议您在一般情况下使用
np.nan
和 float 数组而不是None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.