? Numerical Python. 补充了python所欠缺的数值计算能力
? Numpy是其他数据分析及机器学习库的底层库
? Numpy完全标准C语言实现,运行效率充分优化
? Numpy开源免费
类型名 | 类型表示符 |
---|---|
布尔类型 | bool_ |
有符号整型 | int8/16/32/64 |
无符号整型 | uint8/16/32/64 |
浮点型 | float16/32/64 |
复数型 | complex64/128 |
字符串型 | str_,每个字符32位Unicode |
类似于列表, 可以多维嵌套, 但是要求必须内部存储相同类型的数据
即同质数组, 相同的数据类型的空间占用相同, 且查询方便
ary = np.array([1, 2, 3, 4, 5]) """ _______________________________________ a -----> | nadarray 对象 | | | | 元数据 | |_______ | |_dim___| | |_dtype_| _____________________ | |_data__| ---> |_1_|_2_|_3_|_4_|_5_| | |_shape_| ---> (5,) | |_______|______________________________| """
存储对数组的描述信息, 如 : dim count, dtype, dara, shape 等
完整的数组数据, 将实际数据与元数据分开存放
一方面提高了内存空间的使用效率
另一方面减少对实际数据的访问频率,提高性能。
np.array([[], [], []]) # 直接创建 np.arange(0, 10, 1) # 序列创建 np.zeros(10) # 全 0 创建 np.ones(10) # 全 1 创建 np.zeros_like(ary) # 仿结构创建 全 0 数组 np.ones_like(ary) # 仿结构创建 全 1 数组
import numpy as np a = np.array([1, 2, 3, 4, 5, 6]) print(a) # [1 2 3 4 5 6] b = np.arange(7, 13, 1) print(b) # [ 7 8 9 10 11 12] c = np.zeros(6) print(c) # [ 0. 0. 0. 0. 0. 0.] d = np.ones(6) print(d) # [ 1. 1. 1. 1. 1. 1.] print(d / 2) # [ 0.5 0.5 0.5 0.5 0.5 0.5] e = np.array([[1, 2, 3], [4, 5, 6]]) print(np.ones_like(e)) """ [[1 1 1] [1 1 1]] """
可以直接进行更改数组结构
但是更改需要合理, 比如 6 元素 更改为 3*3 需要9元素则无法满足从而报错
ary = np.array([1, 2, 3, 4, 5, 6]) print(ary, ary.shape) # [1 2 3 4 5 6] (6,)
ary.shape = (2, 3) print(ary, ary.shape) """ [[1 2 3] [4 5 6]] (2, 3) """ print(ary[1][1]) # 5
数据类型直接更改是不可取的, 需要使用 astype 方法进行更改
利用重新开辟新的空间来赋值存储
即此方法不会改变原值, 需要用返回值进行复制
# 数组元素类型 ary = np.array([1, 2, 3, 4, 5, 6]) print(ary, ary.dtype) # [1 2 3 4 5 6] int32
# ary.dtype = np.int64 # print(ary, ary.dtype)
# 更改数据类型 b = ary.astype(‘float32‘) print(ary, ary.dtype) # [1 2 3 4 5 6] int32 print(b, b.dtype) # [ 8.58993459e+09 1.71798692e+10 2.57698038e+10] float32
ary = np.array([1, 2, 3, 4, 5, 6]) print(ary.size) # 6 print(len(ary)) # 6
# 数组元素的索引 ary = np.arange(1, 9) ary.shape = (2, 2, 2) print(ary, ary.shape) """ [[[1 2] [3 4]] [[5 6] [7 8]]] (2, 2, 2) """ print(ary[0]) # 0页数据 """ [[1 2] [3 4]] """ print(ary[0][0]) # 0页0行数据 """ [1 2] """ print(ary[0][0][0]) # 0页0行0列数据 """ 1 """ print(ary[0, 0, 0]) # 0页0行0列数据 """ 1 """ # 使用for循环,把ary数组中的元素都遍历出来。 for i in range(ary.shape[0]): for j in range(ary.shape[1]): for k in range(ary.shape[2]): print(ary[i, j, k], end=‘ ‘) # 1 2 3 4 5 6 7 8
遍历所有的元素进行运算
# ary = np.array([1, 2, 3, 4, 5]) print(ary + 2) # [3 4 5 6 7] print(ary + ary) # [ 2 4 6 8 10] print(ary * ary) # [ 1 4 9 16 25]
遍历所有元素进行比较
# ary = np.array([1, 2, 3, 4, 5]) print(ary > 3) # [False False False True True]
原文:https://www.cnblogs.com/shijieli/p/10846772.html