NumPy shape()

shape() 方法返回数组的形状,即每个维度的元素数量。

示例

import numpy as np

array = np.array([[0, 1], [2, 3]])

# return shape of the array shapeOfArray = np.shape(array)
print(shapeOfArray) # Output : (2, 2)

shape() 语法

shape() 的语法是

numpy.shape(array)

shape() 参数

shape() 方法接受一个参数

  • array - 要确定其形状的数组

shape() 返回值

shape() 方法以元组的形式返回数组的形状。


示例 1:数组的形状

import numpy as np

# create 1D and 2D arrays
array1 = np.array([0, 1, 2, 3])
array2 = np.array([[8, 9]])

# shape of array1 shape1 = np.shape(array1)
print('Shape of the first array : ', shape1)
# shape of array2 shape2 = np.shape(array2)
print('Shape of the second array : ', shape2)

输出

Shape of the first array :  (4,)
Shape of the second array :  (1, 2)

示例 2:元组数组的形状

import numpy as np

# array of tuples
array1 = np.array([(0, 1), ( 2, 3)])

dataType = [('x', int), ('y', int)]

# dtype sets each tuple as an individual array element
array2 = np.array([(0, 1), ( 2, 3)], dtype = dataType)

# shape of array1 shape1 = np.shape(array1)
print('Shape of first array : ', shape1)
# shape of array2 shape2 = np.shape(array2)
print('Shape of second array : ', shape2)

输出

Shape of first array :  (2, 2)
Shape of second array :  (2, )

这里,array1array2 是具有元组作为其元素的 **2** 维数组。 array1 的形状是 (2, 2)。

然而,array2 的形状是 (2, ),这是一维的。

这是因为我们传递了 dtype 参数,它限制了 array2 的结构。

array2 包含两个元素,每个元素都是一个具有两个整数值的元组,但每个元素被视为一个具有两个字段 xy 的单一实体。

因此,array2 是一维的,有两行一列。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战