← 返回首页
多维数组
发表时间:2024-01-16 01:37:28
多维数组

多维数组。

多维数组

实例:

import numpy as np
# 数组维度
#创建一维数组
a1 = np.array([1,2,3])
## 维度为1
print(a1.ndim)
#数组形状查询
print(a1.shape)
#创建二维数组
a2 = np.array([[1,2,3],[4,5,6]])
## 维度为2
print(a2.ndim)
#数组形状查询
print(a2.shape)
#获取行数和列数
print(a2.shape[0])
print(a2.shape[1])
#创建三维数组
## 维度为3
a3 = np.array([
    [
        [1,2,3],
        [4,5,6]
    ],
    [
        [7,8,9],
        [10,11,12]
    ]
])
print(a3.ndim)
#数组形状查询
print(a3.shape)

#修改数组形状
a3 = a3.reshape((2,6))
print(a3)

print(a3.ndim)
#数组形状查询
print(a3.shape)

# 扁平化 (多维数组转化为一维数组)
a3 = a3.flatten()
print(a3)
print(a3.ndim)

#数组的元素个数
count = a3.size
print(count)
#各元素所占内存
print(a3.itemsize)
#各元素数据类型
print(a3.dtype)
#数组所占内存
print(a3.itemsize * a3.size)

1
(3,)
2
(2, 3)
2
3
3
(2, 2, 3)
[[ 1  2  3  4  5  6]
 [ 7  8  9 10 11 12]]
2
(2, 6)
[ 1  2  3  4  5  6  7  8  9 10 11 12]
1
12
4
int32
48

小结: