Python NumPy中ndarray对象的创建、数据类型及基本属性详解
numpy库
numpy是 Python 中用于科学计算的基础库,它提供了高性能的多维数组对象和处理这些数组的工具。
numpy中的数据结构
ndarray
ndarray中的dtype

ndarray中的dtype的指定方式
创建ndarray及指定dtype
从列表创建ndarray
code:
import numpy as np
nd_list = np.array([1, 2, 3, 4, 5, 6], dtype=np.float32)
nd_list_1 = nd_list.astype("int64") # 使用astype重新指定数据类型
print("-------------------- list创建ndarray --------------------")
print("%s: class: %s, dtype: %s, shape: %s, data: %s"
% ("nd_list", type(nd_list), nd_list.dtype, nd_list.shape, nd_list))
print("%s: class: %s, dtype: %s, shape: %s, data: %s"
% ("nd_list_1", type(nd_list_1), nd_list_1.dtype, nd_list_1.shape, nd_list_1))
result:
nd_list: class: <class 'numpy.ndarray'>, dtype: float32, shape: (6,), data: [1. 2. 3. 4. 5. 6.]
nd_list_1: class: <class 'numpy.ndarray'>, dtype: int64, shape: (6,), data: [1 2 3 4 5 6]
code:
import numpy as np
dt = np.dtype([
('name', 'U3'), # Unicode字符串,最大长度3
('age', np.int32),
('height', float)
])
arr = np.array([
('Alice', 25, 1.65),
('Bob', 30, 1.80),
('Charlie', 22, 1.75)
], dtype=dt)
print(arr)
result:
[('Ali', 25, 1.65) ('Bob', 30, 1.8 ) ('Cha', 22, 1.75)]
使用 np.empty(), np.zeros(), np.ones() 和 np.full() 创建特定值的数组
code:
import numpy as np
nd_0 = np.zeros(shape=(2, 3), dtype="int16") # # 在创建时指定dtype, "int16"指明类型
print("-------------------- np.zeros, np.ones, np.full 创建ndarray --------------------")
print("%s: class: %s, dtype: %s, shape: %s, data: %s" % ("nd_0", type(nd_0), nd_0.dtype, nd_0.shape, nd_0))
nd_1 = np.ones(shape=(3, 1), dtype="i1") # 在创建时指定dtype, "i1"指明类型为int8
print("%s: class: %s, dtype: %s, shape: %s, data: %s" % ("nd_1", type(nd_1), nd_1.dtype, nd_1.shape, nd_1))
nd_full = np.full(shape=(2, 1), fill_value=168, dtype=np.int16) # fill_value为要填充的数据, np.int16指明数据类型
print("%s: class: %s, dtype: %s, shape: %s, data: %s" % ("nd_full", type(nd_full), nd_full.dtype, nd_full.shape, nd_full))
result:
-------------------- np.zeros, np.ones, np.full 创建ndarray --------------------
nd_0: class: <class 'numpy.ndarray'>, dtype: int16, shape: (2, 3), data: [[0 0 0]
[0 0 0]]
nd_1: class: <class 'numpy.ndarray'>, dtype: int8, shape: (3, 1), data: [[1]
[1]
[1]]
nd_full: class: <class 'numpy.ndarray'>, dtype: int16, shape: (2, 1), data: [[168]
[168]]
使用 np.arange() 创建等差数列数组
code:
import numpy as np
nd_arr = np.arange(start=0.1, stop=0.5, step=0.1, dtype=np.float16)
print("-------------------- np.arange() 创建等差数列数组 --------------------")
print("%s: class: %s, dtype: %s, shape: %s, data: %s" % ("nd_arr", type(nd_arr), nd_arr.dtype, nd_arr.shape, nd_arr))
result:
-------------------- np.arange() 创建等差数列数组 --------------------
nd_arr: class: <class 'numpy.ndarray'>, dtype: float16, shape: (4,), data: [0.1 0.2 0.2998 0.4 ]
使用 np.linspace() 创建等差数组
code:
import numpy as np
nd_ls, step = np.linspace(start=0.5, stop=5, num=10, endpoint=True, retstep=True, dtype="f2")
print("-------------------- np.linspace() 创建等差数列数组 --------------------")
print("%s: class: %s, dtype: %s, shape: %s, data: %s" % ("nd_arr", type(nd_ls), nd_ls.dtype, nd_ls.shape, nd_ls))
print("step: %f" % step)
result:
-------------------- np.linspace() 创建等差数列数组 --------------------
nd_arr: class: <class 'numpy.ndarray'>, dtype: float16, shape: (10,), data: [0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. ]
step: 0.500000
使用np.logspace()创建等比数组
使用np.random创建随机数组
创建均匀分布的数组
code:
import numpy as np
nd1 = np.random.rand(3, 2)
print("shape: %s, data: %s" % (nd1.shape, nd1))
result:
shape: (3, 2), data: [[0.35805948 0.04036108]
[0.31759615 0.63327184]
[0.6510774 0.60556358]]
code:
import numpy as np
uniform_arr = np.random.uniform(1, 5, (2, 3))
print("-------------------- np.random.uniform 创建矩阵 --------------------")
print(uniform_arr)
result:
-------------------- np.random.uniform 创建矩阵 --------------------
[[4.64121004 3.59098984 4.8255174 ]
[2.66992313 2.69148975 4.1177286 ]]
创建正态分布的数组
code:
import numpy as np
# 使用 np.random.randn() 创建二维数组
randn_arr = np.random.randn(2, 2)
print("使用 np.random.randn() 创建数组")
print(randn_arr)
# 使用 np.random.normal() 创建一维数组,均值为 2,标准差为 0.5
normal_arr = np.random.normal(loc=2, scale=0.5, size=(2, 2))
print("\n使用 np.random.normal() 创建数组")
print(normal_arr)
result:
使用 np.random.randn() 创建数组
[[ 2.2055985 -0.25213918]
[ 0.39241543 -0.54152386]]
使用 np.random.normal() 创建数组
[[1.664472 2.1370329 ]
[2.00500439 1.44690644]]
生成随机整数
code:
import numpy as np
# 创建二维数组,元素取值范围在 [1, 10)
randint_arr = np.random.randint(low=1, high=10, size=(2, 3))
print("使用 np.random.randint() 创建的数组:")
print(randint_arr)
result:
使用 np.random.randint() 创建的数组:
[[1 1 6]
[9 7 1]]
随机选择元素
code:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# 从数组中随机选择元素, 形成指定size的数组,允许重复选择
choice_arr = np.random.choice(a=arr, size=(2, 2), replace=True)
print("使用 np.random.choice() 随机选择的元素:", choice_arr)
result:
使用 np.random.choice() 随机选择的元素: [[3 5]
[1 4]]
创建单位阵
code:
import numpy as np
# 创建 3x3 的单位矩阵
square_eye = np.eye(3)
print("3x3 的单位矩阵:")
print(square_eye)
# 创建 2x3 的矩阵,主对角线为 1
rectangular_eye = np.eye(2, 3)
print("\n2x3 的矩阵,主对角线为 1:")
print(rectangular_eye)
# 创建 3x3 的矩阵,对角线向右上方偏移 1 位
shifted_diagonal_eye = np.eye(3, k=1)
print("\n3x3 的矩阵,对角线向右上方偏移 1 位:")
print(shifted_diagonal_eye)
# 创建 3x3 的矩阵,对角线向左下方偏移 1 位
negative_shifted_diagonal_eye = np.eye(3, k=-1)
print("\n3x3 的矩阵,对角线向左下方偏移 1 位:")
print(negative_shifted_diagonal_eye)
result:
3x3 的单位矩阵:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
2x3 的矩阵,主对角线为 1:
[[1. 0. 0.]
[0. 1. 0.]]
3x3 的矩阵,对角线向右上方偏移 1 位:
[[0. 1. 0.]
[0. 0. 1.]
[0. 0. 0.]]
3x3 的矩阵,对角线向左下方偏移 1 位:
[[0. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]]
ndarray的基本属性
code:
import numpy as np
nd1 = np.full((1, 3), 666)
print("nd1:", nd1)
print("shape:", nd1.shape)
print("size: %d" % nd1.size)
print("ndim: %d" % nd1.ndim)
nd2 = np.linspace(2, 3, 3)
print("nd2:", nd2)
print("shape:", nd2.shape)
result:
nd1: [[666 666 666]]
shape: (1, 3)
size: 3
ndim: 2
nd2: [2. 2.5 3. ]
shape: (3,)
作者:weixin_48668114