Skip to content

N 维数组-ndarray

1 ndarray 的属性

数组属性反映了数组本身固有的信息。

属性名字属性解释
ndarray.shape数组维度的元组
ndarray.ndim数组维数
ndarray.size数组中的元素数量
ndarray.itemsize一个数组元素的长度(字节)
ndarray.dtype数组元素的类型

2 ndarray 的形状

首先创建一些数组。

python
# 创建不同形状的数组
>>> a = np.array([[1,2,3],[4,5,6]])
>>> b = np.array([1,2,3,4])
>>> c = np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
# 创建不同形状的数组
>>> a = np.array([[1,2,3],[4,5,6]])
>>> b = np.array([1,2,3,4])
>>> c = np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])

分别打印出形状

python
>>> a.shape
>>> b.shape
>>> c.shape

(2, 3)  # 二维数组
(4,)    # 一维数组
(2, 2, 3) # 三维数组
>>> a.shape
>>> b.shape
>>> c.shape

(2, 3)  # 二维数组
(4,)    # 一维数组
(2, 2, 3) # 三维数组

如何理解数组的形状?

二维数组:

三维数组:

3 ndarray 的类型

python
>>> type(score.dtype)

<type 'numpy.dtype'>
>>> type(score.dtype)

<type 'numpy.dtype'>

dtype 是 numpy.dtype 类型,先看看对于数组来说都有哪些类型

名称描述简写
np.bool用一个字节存储的布尔类型(True 或 False)'b'
np.int8一个字节大小,-128 至 127'i'
np.int16整数,-32768 至 32767'i2'
np.int32整数,-2^31​ 至 2^32 -1'i4'
np.int64整数,-2^63 至 2^63 - 1'i8'
np.uint8无符号整数,0 至 255'u'
np.uint16无符号整数,0 至 65535'u2'
np.uint32无符号整数,0 至 2^32 - 1'u4'
np.uint64无符号整数,0 至 2^64 - 1'u8'
np.float16半精度浮点数:16 位,正负号 1 位,指数 5 位,精度 10 位'f2'
np.float32单精度浮点数:32 位,正负号 1 位,指数 8 位,精度 23 位'f4'
np.float64双精度浮点数:64 位,正负号 1 位,指数 11 位,精度 52 位'f8'
np.complex64复数,分别用两个 32 位浮点数表示实部和虚部'c8'
np.complex128复数,分别用两个 64 位浮点数表示实部和虚部'c16'
np.object_python 对象'O'
np.string_字符串'S'
np.unicode_unicode 类型'U'

创建数组的时候指定类型

python
>>> a = np.array([[1, 2, 3],[4, 5, 6]], dtype=np.float32)
>>> a.dtype
dtype('float32')

>>> arr = np.array(['python', 'tensorflow', 'scikit-learn', 'numpy'], dtype = np.string_)
>>> arr
array([b'python', b'tensorflow', b'scikit-learn', b'numpy'], dtype='|S12')
>>> a = np.array([[1, 2, 3],[4, 5, 6]], dtype=np.float32)
>>> a.dtype
dtype('float32')

>>> arr = np.array(['python', 'tensorflow', 'scikit-learn', 'numpy'], dtype = np.string_)
>>> arr
array([b'python', b'tensorflow', b'scikit-learn', b'numpy'], dtype='|S12')
  • 注意:若不指定,整数默认 int64,小数默认 float64