# 数据处理-numpy

# Anaconda 环境安装

# 下载合适版本 Anaconda3-2022.05-MacOSX-arm64.pkg 一键安装
https://repo.anaconda.com/archive/

# 配置启动目录 最后行添加 export
vim /etc/profile
export PATH=/Users/nining/opt/anaconda3/bin:$PATH
source /etc/profile

# 启动服务 展示当前目录文件
mkdir -p /Users/nining/notebook
cd /Users/nining/notebook
jupyter-notebook

# Jupyter 单元格操作

# 单元格基本状态
预览状态 esc  <---> 编辑状态 enter
Code模式 y   <---> Markdown模式 m

# 增删改查 快捷键
执行 ctrl + enter
新增 a上增 b下增
删除 dd
复制 c
粘贴 v
剪贴 x
撤销 z
帮助 help(len) 或者 len? obj=shift+tab

# Jupyter 魔法指令

# 加载 tools 中定义的对象
%run tools.py

# Numpy 功能介绍

  • 一个基于 Python 的扩展库
  • 提供多维度数组对象 ndarray,运算速度碾压 Python list
  • 提供各种高级数据编程工具,如矩阵运算、向量运算、快速筛选、IO操作、傅里叶变换、线性代数、随机数等
arr = np.array([[1, 2, 3], [2,3, 4]])
arr.ndim    # 维度 2
arr.shape   # (2, 3)  -> 最外层 2 个
arr.size    # 元素总个数
arr.dtype   # dtype('int64')) 元素类型,强制统一
  • 强制类型统一
1. numpy 设计初衷是为了运算,所以对数据类型进行统一优化
2. 默认ndarray所有数据类型是相同的,不同则统一类型,优先级:str > float > int

# Numpy 工厂函数

多维数组,即矩阵,常用函数用来按照指定规则生成多维数组

  • np.ones(shape, dtype=None, order='C') 填充1
np.ones(shape=(3, 1))
np.ones(shape=(1, 3))
np.ones(shape=(3, ))
np.ones(shape=3)
arr = np.ones(shape=3, dtype=np.int8, order='C')
arr.ndim
arr.shape
arr.size
arr.dtype

# order='C' 几乎不变
  • np.zeros(shape, dtype=None, order='C') 填充0
  • np.full(shape, fill_value=None, order='C') 自定义填充值 fill_value
  • np.eye(N, M=None, k=0, dtype=fload) \ 对角线为1,M表示列,k表示便宜
np.eye(N=3)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
  • 较重要 np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
生成等差数列
start, stop 开始结束值  num 表示总数 endpoint 是否包括最后值

np.linspace(0, 360, 4, endpoint=False)
array([  0.,  90., 180., 270.])
  • 较重要 np.arange([start,] stop, [step,] dtype=None) 和range类似
  • np.random.randint(low, high=None, size=None, dtype='I) 这里的size其实是shape
np.random.randint(low=0, high=100, size=(3, 2))
np.random.randint(low=0, high=100, size=(3, ))
  • np.random.randn(3, 2, ...) 标准正态分布 loc=0, scale=1
  • np.random.normal 普通正态分布
np.random.normal(loc=175, scale=10, size=(2, 2))
  • np.random.random(size=None)
生成0到1的随机数,左闭右开
size,即shape
  • np.random.permutation(10) 生成随机索引
  • np.random.seed(1) 随机种子

# Numpy 读写操作

  • 索引访问
arr = np.random.randint(0, 10, size=(3, 4))
display(arr)
array([[4, 8, 1, 4],
       [0, 3, 9, 2],
       [0, 4, 9, 2]])
# 类似 list 访问
arr[2][1]  # 4

# ndarray高维数组独有访问方式,[dim1_index, dim2_index, ...],推荐方式
arr[2, 1]

# 区别在于 arr[2] 是中间 array([0, 4, 9, 2]) 这个对象,有安全隐患,不提倡
  • 列表访问
# 平常索引访问传入int即可,ndarray可以传入索引列表,返回多个对应值
arr[[0, 1]]
array([[4, 8, 1, 4],
       [0, 3, 9, 2]])
# 逆天操作
arr[[0, 1, 0, 1]]
  • 切片访问
# 从后往前
arr[::-1]
array([[0, 4, 9, 2],
       [0, 3, 9, 2],
       [4, 8, 1, 4]])
# 倒数后两行
arr[-2:]
array([[0, 3, 9, 2],
       [0, 4, 9, 2]])
  • 访问小结 访问很灵活
[dim1_index, dim2_index, ..., dim2_index]
1. 整型 int 
2. 列表[int, int]  
3. 切片[int:int]
4. bool列表 [False, True, ..., True] 输出 True 对应值
甚至可以组合使用

# 取其前两列
arr[:, [0, 1]]
array([[4, 8],
       [0, 3],
       [0, 4]])

# Numpy 级联与切分

  • 级联 把多个数组合并为一个
arr1 = np.random.randint(0, 10, size=(3, 4))
arr2 = np.random.randint(10, 20, size=(3, 4))
display(arr1, arr2)
array([[3, 0, 8, 7],
       [7, 1, 1, 3],
       [0, 8, 6, 4]])
array([[15, 16, 12, 15],
       [17, 18, 14, 14],
       [17, 17, 14, 19]])

# 在级联的维度上,元素个数要一致
# (arr1, arr2) 参数为元组
np.concatenate((arr1, arr2), axis=0)
array([[ 3,  0,  8,  7],
       [ 7,  1,  1,  3],
       [ 0,  8,  6,  4],
       [15, 16, 12, 15],
       [17, 18, 14, 14],
       [17, 17, 14, 19]])

# 竖着级联
np.vstack((arr1, arr2))

# 横着级联
np.hstack((arr1, arr2))
  • 拆分 把一个数组拆分为多个
# indices_or_sections = N,行方向切分为N等份
np.split(arr, indices_or_sections=2, axis=0)

# indices_or_sections = [M: N],按照[0:M),[M,), [N:)切分
np.split(arr, indices_or_sections=[2], axis=1)

# 切纵轴
np.vsplit

# 切横轴
np.hsplit

data = np.random.randint(0, 10, size=5)
data.dtype  # dtype('int64')

# 每个元素转换为指定格式
data.astype(np.float64)

# Numpy 基本运算

  • 基本运算规则
1. 两个矩阵运算,就是对应位置的数据运算
2. 不单单是算术运算,+ - * /,其他的 > <= == 也是可以
  • 广播规则,即ndarray运算规则
如果
1. 两个数组的后缘维度(tailing dimension,即从末尾开始算起的维度)的轴长度相符
2. 或其中一方的长度为1
则认为它们是广播兼容的,就会广播为shape相同的矩阵,然后运算
# 后缘维度轴长度相符
a = np.ones((2, 3))
b = np.arange(3)
a + b

# 其中一方的长度为1
a = np.arange(3).reshape((3, 1))
b = np.arange(3)
display(a, b)
(array([[0],
        [1],
        [2]]),
 array([0, 1, 2]))

a + b
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

# 常数可认为维度为0,兼容任意矩阵
a + 1
b + 1

# Numpy 聚合运算

data = np.random.randint(0, 100, size=5)
# 整个数组和
data.sum()

data = np.random.randint(0, 100, size=(3, 2))
array([[37, 72],
       [43, 24],
       [16, 96]])
# 行方向求和,即竖着加
data.sum(axis=0)
array([ 96, 192])

# 列方向求和,即横着加
data.sum(axis=1)
array([109,  67, 112])

# 空值
type(np.nan)    # float 类型
np.nan + 1      # 任何值和np.nan运算都为nan

data.sum()      np.nansum(data)     # 求和
data.prod()     np.nanprod(data)    # 求即
data.mean()     np.nanmean(data)    # 求均值
data.std()      np.nanstd()     
data.min()      np.nanmin()
data.max()      np.nanmax()

data.any()
data.all()

# Numpy 增删改查

``
上次更新: 12/1/2022, 7:02:59 PM