Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

NumPy 数组形状


数组的形状

数组的形状是每个维度中元素的数量。


获取数组的形状

NumPy 数组有一个名为 shape 的属性,它返回一个元组,每个索引都包含对应元素的数量。

示例

打印一个二维数组的形状

import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

print(arr.shape)
亲自尝试 »

上面的示例返回 (2, 4),这意味着数组有 2 个维度,第一个维度有 2 个元素,第二个维度有 4 个元素。

示例

使用 ndmin 创建一个具有 5 个维度的数组,使用值为 1,2,3,4 的向量,并验证最后一个维度值为 4

import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)
print('数组的形状 :', arr.shape)
亲自尝试 »

形状元组代表什么?

每个索引处的整数表示对应维度具有的元素数量。

在上面的示例中,索引 4 处的值为 4,因此我们可以说第 5 个(4 + 1 个)维度有 4 个元素。



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.