Skip to content

NumPy - 数组属性

NumPy 数组(ndarray 对象)有几个有用的属性,无需检查数据本身即可提供有关数组结构和数据的信息。这些属性对于有效理解和操作数组至关重要。

返回一个元组,指示数组沿每个维度的尺寸。对于二维数组(矩阵),它返回 (行数, 列数)。对于一维数组,它返回 (元素个数,)。

您也可以设置 shape 属性来就地改变数组形状,但元素的总数必须保持不变。如果可能,此操作会创建一个视图 (view),修改对现有数据的解释方式。

import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(f"Array:\n{a}")
print(f"Shape: {a.shape}")
b = np.array([10, 20, 30])
print(f"\nArray:\n{b}")
print(f"Shape: {b.shape}")

输出:

Array:
[[1 2 3]
[4 5 6]]
Shape: (2, 3)
Array:
[10 20 30]
Shape: (3,)

示例 2:设置 shape(就地改变形状)

Section titled “示例 2:设置 shape(就地改变形状)”

通过给 shape 属性赋值来改变数组形状:

# Reshape the array by assigning to the shape attribute
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]]) # Total 6 elements
print(f"Original array (shape {a.shape}):\n{a}\n")
# Reshape in-place to 3 rows, 2 columns (still 6 elements)
try:
a.shape = (3, 2)
print(f"Reshaped array (shape {a.shape}):\n{a}")
except ValueError as e:
print(f"Error reshaping: {e}")
# Attempting incompatible shape
try:
print("\nAttempting to reshape to (3, 3) (9 elements)")
a.shape = (3, 3) # This will fail
except ValueError as e:
print(f"Error: {e}")

输出:

Original array (shape (2, 3)):
[[1 2 3]
[4 5 6]]
Reshaped array (shape (3, 2)):
[[1 2]
[3 4]
[5 6]]
Attempting to reshape to (3, 3) (9 elements)
Error: cannot reshape array of size 6 into shape (3,3)

NumPy 还提供了 reshape() 方法,它返回一个新数组(通常是视图,但有时是副本),具有指定的形状。原始数组保持不变。

import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(f"Original array 'a' (shape {a.shape}):\n{a}\n")
# Create a new array 'b' with shape (3, 2)
b = a.reshape(3, 2)
print(f"New array 'b' (shape {b.shape}):\n{b}\n")
print(f"Original array 'a' remains unchanged:\n{a}")

输出:

Original array 'a' (shape (2, 3)):
[[1 2 3]
[4 5 6]]
New array 'b' (shape (3, 2)):
[[1 2]
[3 4]
[5 6]]
Original array 'a' remains unchanged:
[[1 2 3]
[4 5 6]]

返回数组的维度数量(轴数)。例如,一维数组的 ndim=1,二维数组的 ndim=2。

import numpy as np
# Create an array of numbers from 0 to 23
a = np.arange(24)
print(f"Array 'a':\n{a}")
print(f"Number of dimensions (a.ndim): {a.ndim}\n")
# Reshape 'a' into a 3D array (2 layers, 4 rows, 3 columns)
b = a.reshape(2, 4, 3)
print(f"Reshaped array 'b':\n{b}")
print(f"Number of dimensions (b.ndim): {b.ndim}")

输出:

Array 'a':
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
Number of dimensions (a.ndim): 1
Reshaped array 'b':
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[12 13 14]
[15 16 17]
[18 19 20]
[21 22 23]]]
Number of dimensions (b.ndim): 3

返回数组中元素的总数。这等于 shape 元组中元素的乘积。

import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(f"Array:\n{a}")
print(f"Shape: {a.shape}")
print(f"Size (total elements): {a.size}") # 2 * 3 = 6

输出:

Array:
[[1 2 3]
[4 5 6]]
Shape: (2, 3)
Size (total elements): 6

返回一个描述数组中元素数据类型 (dtype) 的对象。例如包括 int64、float64、bool、complex128、object 等。

import numpy as np
# Array of integers (defaults to int64 on most systems)
a = np.array([1, 2, 3])
print(f"Array 'a': {a}, dtype: {a.dtype}\n")
# Array of floats (defaults to float64)
b = np.array([1.0, 2.5, 3.14])
print(f"Array 'b': {b}, dtype: {b.dtype}\n")
# Array with specified dtype
c = np.array([1, 0, 1], dtype=bool)
print(f"Array 'c': {c}, dtype: {c.dtype}")

输出:

Array 'a': [1 2 3], dtype: int64
Array 'b': [1. 2.5 3.14], dtype: float64
Array 'c': [ True False True], dtype: bool

返回数组中每个元素的大小(以字节为单位)。例如,float64 数组的 itemsize 是 8(因为 64 位 = 8 字节)。

import numpy as np
# Array with int8 (1 byte per element)
x = np.array([1, 2, 3], dtype=np.int8)
print(f"Array 'x': {x}, dtype: {x.dtype}, itemsize: {x.itemsize} bytes\n")
# Array with float32 (4 bytes per element)
y = np.array([1.0, 2.0, 3.0], dtype=np.float32)
print(f"Array 'y': {y}, dtype: {y.dtype}, itemsize: {y.itemsize} bytes\n")
# Array with default float64 (8 bytes per element)
z = np.array([1.0, 2.0, 3.0])
print(f"Array 'z': {z}, dtype: {z.dtype}, itemsize: {z.itemsize} bytes")

输出:

Array 'x': [1 2 3], dtype: int8, itemsize: 1 bytes
Array 'y': [1. 2. 3.], dtype: float32, itemsize: 4 bytes
Array 'z': [1. 2. 3.], dtype: float64, itemsize: 8 bytes

返回一个对象,其中包含有关数组数据内存布局和属性的信息。主要的 flags 包括:

Flag描述
C_CONTIGUOUS (C)数据以行主序(C 风格)连续存储在内存块中。
F_CONTIGUOUS (F)数据以列主序(Fortran 风格)连续存储在内存块中。
OWNDATA (O)指示数组是否拥有它使用的内存。对于视图(view)则为 False。
WRITEABLE (W)指示数据区域是否可以修改。可以设置为 False 使数组变为只读。
ALIGNED (A)指示数据是否在内存中适当地对齐以适应硬件,这会影响性能。
WRITEBACKIFCOPY (X)以前是 UPDATEIFCOPY (U)。与内部使用的临时副本有关;通常不直接交互。

连续性(C 或 F)会显著影响某些操作的性能,因为在内存中顺序访问元素通常更快。

显示标准数组的 flags:

import numpy as np
x = np.array([1, 2, 3, 4, 5])
print(f"Array 'x': {x}")
print(f"Flags for 'x':\n{x.flags}\n")
# Example of a non-contiguous array (from slicing)
y = x[::2] # Elements 1, 3, 5 (indices 0, 2, 4)
print(f"Array 'y' (a slice): {y}")
print(f"Flags for 'y':\n{y.flags}\n")
# Example of a Fortran-contiguous array
z = np.array([[1,2],[3,4]], order='F')
print(f"Array 'z' (Fortran order):\n{z}")
print(f"Flags for 'z':\n{z.flags}")

输出(可能因 NumPy 版本和系统而略有不同):

Array 'x': [1 2 3 4 5]
Flags for 'x':
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
Array 'y' (a slice): [1 3 5]
Flags for 'y':
C_CONTIGUOUS : False
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
Array 'z' (Fortran order):
[[1 2]
[3 4]]
Flags for 'z':
C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False