Python-numpy中ndarray对象创建,数据类型,基本属性
numpy库
- numpy中的数据结构
- ndarray
- ndarray中的dtype
- ndarray中的dtype的指定方式
- 创建ndarray及指定dtype
- 从列表创建ndarray
- 使用 np.empty(), np.zeros(), np.ones() 和 np.full() 创建特定值的数组
- 使用 np.arange() 创建等差数列数组
- 使用 np.linspace() 创建等差数组
- 使用np.logspace()创建等比数组
- 使用np.random创建随机数组
- 创建均匀分布的数组
- 创建正态分布的数组
- 生成随机整数
- 随机选择元素
- 创建单位阵
- ndarray的基本属性
numpy是 Python 中用于科学计算的基础库,它提供了高性能的多维数组对象和处理这些数组的工具。
numpy中的数据结构
- 🍒 ndarray(N-dimensional array),核心数据结构
- 🍒 结构化数组(Structured Arrays)
- 🍒 记录数组(Record Arrays)
- 🍒 掩码数组(Masked Arrays)
ndarray
- 🍒 同质性:数组中的所有元素必须是相同的数据类型,例如整数、浮点数等。
- 🍒 多维性:可以表示一维、二维、三维甚至更高维度的数组。
- 🍒 高效性:基于连续的内存块存储数据,因此在数值计算方面性能优越。
ndarray中的dtype
- 🍒 dtype(data type,即数据类型)是一个关键概念,它定义了 ndarray 数组中元素的数据类型。
- 🍒 借助 dtype,你能够精准控制数组所占用的内存空间,还能提升计算效率。
- 🍒 可以在创建ndarray时指定dtype。
- 🍒 可以在后面用astype指定,astype并不直接改变原ndarray数据的类型,它会生成新的ndarray。
ndarray中的dtype的指定方式
- 🍒 字符串: “i1”, "int8"等。
- 🍒 np.int16等。
创建ndarray及指定dtype
从列表创建ndarray
- 🍒 np.array(list), 一维或者多维均可。
- 🍒 np.fromiter(iter), 适合大批量数据的处理。
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]
使用 np.empty(), np.zeros(), np.ones() 和 np.full() 创建特定值的数组
- 🍇 np.zeros_like, np.ones_like, np.full_like创建一个与给定的数组维度和数类型相同,并以0或者1或者指定的数据填充的数组。
- 🍇 np.empty()用于创建指定形状和数据类型的数组,但不会对数组元素进行初始化,数组中的元素是未初始化的随机值,这些值取决于内存中该位置之前存储的内容。
- 🍇 np.empty_like用于创建一个与指定数组具有相同维度和相同数据类型且未初始化的数组。
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() 创建等差数列数组
- 🍆 numpy.arange([start, ]stop, [step, ], dtype=None)。
- 🍆 整数和小数都可。
- 🍆 numpy.asarray与其类似。
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() 创建等差数组
- 🌽 np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
- 🌽 num: 指定元素的个数。
- 🌽 endpoint: 指定是否把stop的参数作为最后一个元素。
- 🌽 retstep设置为 True 时,函数除了返回生成的序列外,还会返回样本之间的间距。
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()创建等比数组
- 🥦 numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)
- 🥦 num: 指定元素的个数。
- 🥦 endpoint: 指定是否把stop的参数作为最后一个元素。
- 🥦 base: 指定等比数列的公比,默认值为 10.0。
使用np.random创建随机数组
创建均匀分布的数组
- 🍄 numpy.random.rand(d0, d1, …, dn), 生成指定形状的随机数据,数组元素是在 [0, 1) 区间内均匀分布的随机浮点数。
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]]
- 🍄 numpy.random.uniform(low=0.0, high=1.0, size=None)。指定随机数的取值范围,创建在指定区间内均匀分布的随机数组。
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 ]]
创建正态分布的数组
- 🍄 np.random.randn():创建数组,数组元素服从标准正态分布(均值为 0,标准差为 1)。
- 🍄 randn(d0, d1, …, dn), 可指定形状。
- 🍄 np.random.normal():可以指定均值和标准差,创建服从指定正态分布的随机数数组。
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]]
生成随机整数
- 🍄 np.random.randint():创建指定形状的数组,数组元素是在指定范围内的随机整数。
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]]
随机选择元素
- 🍄 np.random.choice():从给定的一维数组中随机选择元素,可指定选择的元素个数、是否允许重复选择等。
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]]
创建单位阵
- 🍄 使用 np.eye() 创建单位矩阵。
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的基本属性
- 🍑 numpy.shape: 指定数组的形状,返回一个元组或者整数,如果是一维的,返回int类型。
- 🍑 numpy.size: 元素的数量。
- 🍑 numpy.ndim: 数组的维数。
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,)