我有一个简单的脚本,它会返回很多错误:
import numpy as np
def test(array):
ncol=np.shape(array)[1]
return ncol
应该返回数组的列数。这有什么问题?
数组是numpy数组。这是输出:
ncol=np.shape(array)[1]
Display all 195 possibilities? (y or n)
ArithmeticError( continue
AssertionError( copyright(
AttributeError( credits(
BaseException( def
BlockingIOError( del
答案 0 :(得分:1)
您需要在try.. catch
周围添加ncol=np.shape(array)[1]
,因为当数组为1维时它会失败:
import numpy as np
arr = np.random.normal(size=10)
arr1 = np.random.normal(size=(10,5))
def test(array):
try:
ncol=np.shape(array)[1]
return ncol
except Exception as e:
print("no columns in array")
return None
print(test(arr))
# output:
# no columns in array
# None
print(test(arr1))
# output:
# 5