gpt4 book ai didi

python - numpy.ndarray.shape 改变维度

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:44 25 4
gpt4 key购买 nike

保存 numpy 数组 (numpy.ndarray.shape) 维度的元组会更改大小。例如:

len(numpy.array([1,2,3]).shape) -> 1, shape=(1,)
len(numpy.array([[1,2,3],[4,5,6]]).shape) -> 2, shape=(2,3)

是否有其他方法可以使维度与数组类型保持不变?

这是我经常遇到的问题的示例:

mat3D = np.arange(27).reshape(3,3,3)
mat2D = np.arange(9)

def processMatrix(mat):
if M.ndim == 2:
return foo(mat)
else:
return np.array([foo(mat[:,:,c]) for c in range(mat.shape[2])])

拥有 mat2D.shape = (3,3,1) 会将代码简化为:

def processMatrix(mat):
return np.array([foo(mat[:,:,c]) for c in range(mat.shape[2])])

最佳答案

您可以使用

numpy.array([[1,2,3],[4,5,6]]).ndim

关于python - numpy.ndarray.shape 改变维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25045513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com