数组属性

很多时候我们可以声明axis,axis = 0,表示沿着第 0 轴进行操作,即对每一列进行操作; axis=1,表示沿着第 1 轴进行操作,即对每一行进行操作.

ndarray 对象属性:

参数 说明
ndarray.ndim 秩,即轴的数量或维度的数量
ndarray.shape 数组的维度,对于矩阵,n 行 m 列
ndarray.size 数组元素的总个数,相当于.shape中n×m 的值
ndarray.dtype ndarray 对象的元素类型
ndarray.itemsize ndarrray 对象中每一个元素的大小,以字节为单位
ndarray.flags ndarray 对象中的内存信息
ndarray.real ndarray元素的实部
ndarray.imag ndarray 元素的虚部
ndarray.data 包含实际数组元素的缓冲区,由于一般通过数组的索引获取元素,所以通常不需要使用这个属性

ndarray.ndim

返回数组的维度,等于秩

nd_one = np.arange(12)
print('nd_one 的维度为:{}维'.format(nd_one.ndim))    # 输出结果为:nd_one 的维度为:1维
nd_three = nd_one.reshape(2,3,2)
print('nd_three的维度为:{}维'.format(nd_three.ndim))    # 输出结果为:nd_three的维度为:3维

ndarray.shape

返回数组的位数,返回一个元祖,这个元祖的长度就是维度的数目,即 ndim 属性(秩)

nd_sh = np.array([[1, 2, 3],[4, 5, 6]])
print('nd_sh 的维度为:{}'.format(nd_sh.shape))  # 输出结果为:nd_sh 的维度为:(2, 3)

ndarray.shape也可以用于调整数组大小

nd_sh = np.array([[1, 2, 3],[4, 5, 6]])
print('调整数组大小前,nd_sh:\n{}'.format(nd_sh))
nd_sh.shape = (3,2)
print('调整数组大小后,nd_sh:\n{}'.format(nd_sh))

# 输出结果:
# 调整数组大小前,nd_sh:
# [[1 2 3]
#  [4 5 6]]
# 调整数组大小后,nd_sh:
# [[1 2]
#  [3 4]
#  [5 6]]

reshape()函数也可用于调整数组大小

nd_sh = np.array([[1, 2, 3],[4, 5, 6]])
print('调整数组大小前,nd_sh:\n{}'.format(nd_sh))
nd_sh_new = nd_sh.reshape(3,2)
print('调整数组大小后,nd_sh_new:\n{}'.format(nd_sh_new))

# 输出结果:
# 调整数组大小前,nd_sh:
# [[1 2 3]
#  [4 5 6]]
# 调整数组大小后,nd_sh_new:
# [[1 2]
#  [3 4]
#  [5 6]]

ndarray.itemsize

以字节的形式返回数组中每一个元素的大小

int_size = np.array([1, 2, 3, 4, 5], dtype = np.int64)
print('int_size的 itemsize 为:{}'.format(int_size.itemsize))
float_size = np.array([1, 2, 3, 4, 5],dtype = np.float16)
print('float_size的 itemsize 为:{}'.format(float_size.itemsize))

# 输出结果:
# int_size的 itemsize 为:8
# float_size的 itemsize 为:2