前言:个人随手笔记,有误请留言
1. 生成数组的方法
1.1 生成0和1的数组
np.ones(shape, dtype)
np.ones_like(a, dtype) # 变换
np.zeros(shape, dtype)
np.zeros_like(a, dtype) # 变换
> 参数说明:shape 数组形状 dtype数组类型
名称 | 描述 | 简写 |
---|---|---|
np.bool | 用一个字节存储的布尔类型(True或False) | ‘b’ |
np.int8 | 一个字节大小,-128 至 127 | ‘i’ |
np.int16 | 整数,-32768 至 32767 | ‘i2’ |
np.int32 | 整数,-2^31 至 2^32 -1 | ‘i4’ |
np.int64 | 整数,-2^63 至 2^63 - 1 | ‘i8’ |
np.uint8 | 无符号整数,0 至 255 | ‘u’ |
np.uint16 | 无符号整数,0 至 65535 | ‘u2’ |
np.uint32 | 无符号整数,0 至 2^32 - 1 | ‘u4’ |
np.uint64 | 无符号整数,0 至 2^64 - 1 | ‘u8’ |
np.float16 | 半精度浮点数:16位,正负号1位,指数5位,精度10位 | ‘f2’ |
np.float32 | 单精度浮点数:32位,正负号1位,指数8位,精度23位 | ‘f4’ |
np.float64 | 双精度浮点数:64位,正负号1位,指数11位,精度52位 | ‘f8’ |
np.complex64 | 复数,分别用两个32位浮点数表示实部和虚部 | ‘c8’ |
np.complex128 | 复数,分别用两个64位浮点数表示实部和虚部 | ‘c16’ |
np.object_ | python对象 | ‘O’ |
np.string_ | 字符串 | ‘S’ |
np.unicode_ | unicode类型 | ‘U’ |
1.2 从现有数组生成
1.2.1 生成方式
np.array(object, dtype) =>深拷贝
np.asarray(a, dtype) => 浅拷贝
###### 区别:是否开辟新内存地址
1.3 生成固定范围的数组
1.3.1 创建等差数组 — 指定数量
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
说明: endpoint 是否要包含stop ,retstep 是否显示步长
1.3.2 创建等差数组 — 指定步长
np.arange(start=None, stop=None, step=None, dtype=None)
1.3.3 创建等比数列
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
说明: endpoint 是否要包含stop ,base 底数
1.4 生成随机数组
1.4.1 使用模块介绍
- np.random模块
1.4.2 正态分布
np.random.randn(d0, d1, …, dn) # 功能:从标准正态分布中返回一个或多个样本值
np.random.normal(loc=0.0, scale=1.0, size=None) # 功能:从正态分布中返回一个或多个样本值
np.random.standard_normal(size=None) # 功能:返回指定形状的标准正态分布的数组。
说明:,由size控制数组形状 参数选择:int or tuple of ints
1.4.3 均匀分布
np.random.rand(d0, d1, …, dn) # 功能:返回[0.0,1.0)内的一组均匀分布的数。
np.random.uniform(low=0.0, high=1.0, size=None) # 左闭右开 功能:从一个均匀分布[low,high)中随机采样
np.random.randint(low, high=None, size=None, dtype='l') # 左闭右开 功能:从一个均匀分布中随机采样,生成一个整数或N维整数数组
说明:
对于例3
取数范围:若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数。
2 数组的索引、切片
- 直接进行索引,切片
- 对象[:, :] –
举例:
#二维的数组,两个维度
stock_change[0, 0:3]
#三维
a1 = np.array([ [[1,2,3],[4,5,6]], [[12,3,34],[5,6,7]]])
#返回结果
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[12, 3, 34],
[ 5, 6, 7]]])
#索引、切片
>>> a1[0, 0, 1] # 输出: 2
3 形状修改
3.1 返回一个具有相同数据域,但shape不一样的视图
ndarray.reshape(shape, order)
返回新的数组
3.2 修改数组本身的形状(需要保持元素个数前后相同)
ndarray.resize(new_shape)
直接修改原有数组
3.3 数组的转置
ndarray.T
实质 : 行列转换
4 类型修改
4.1 ndarray.astype(type)
返回修改了类型之后的数组
stock_change.astype(np.int32)
4.2 ndarray.tostring([order])或者ndarray.tobytes([order])
构造包含数组中原始数据字节的Python字节
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[12, 3, 34], [5, 6, 7]]])
arr.tostring()
5 数组的去重
5.1 np.unique()
temp = np.array([[1, 2, 3, 4],[3, 4, 5, 6]])
>>> np.unique(temp)
array([1, 2, 3, 4, 5, 6])