【Python】Numpy(学习笔记)

一、Numpy概述

1、Numpy

Numpy(Numerical Python)是一个开源的Python科学计算库,用于快速处理任意维度的数组。

Numpy使用ndarray对象来处理多维数组,该对象是一个快速而灵活的大数据容器,

Numpy

  • num - numerical 数值化的
  • py - python

ndarray

  • n - 任意个
  • d - dimension 维度
  • array - 数组

2、ndarray优势

ndarray比原生list运行效率高

存储风格

  • ndarray - 相同类型 - 通用性不强
  • list - 不同类型 - 通用性很强

并行化运算

ndarray支持并行化运算(向量化运算)

底层语言

C语言,解除了GIL(全局解释器索)

3、ndarray属性

shape:数组维度的元组

ndim:数组维度

size:数组中的元素数量

itemsize:一个数组元素的长度

dtype:数组元素的类型

在创建ndarray的时候,如果没有指定类型

默认:整数 int64、浮点数 float64

二、基本操作

1、模块导入

python 复制代码
import numpy as np

2、生成数组的方法

1)生成0和1

python 复制代码
np.zeros(shape)
np.ones(shape)

2)从现有数组中生成

python 复制代码
# 深拷贝
np.array()
np.copy()

# 浅拷贝
np.asarray()

3)生成固定范围的数组

python 复制代码
# [a, b] 数量c
np.linspace(a, b, c)
# [a, b) 步长c
np.arange(a, b, c)

4)生成随机数组

均匀分布:每组的可能性相等

正态分布:μ、σ

python 复制代码
# 均匀分布 (a, b) 数量c
np.random.uniform(a, b, c)

# 正态分布 数量c
np.random.normal(μ, σ, c)

3、数组的索引、切片

python 复制代码
score[0, :3]
score[1, 1]

4、形状修改

python 复制代码
ndarray.reshape(shape) 	# 返回新的ndarray,原始数据没有改变
ndarray.resize(shape) 	# 没有返回值,对原始的ndarray进行了修改
ndarray.T 				# 转置 行变成列,列变成行

5、类型修改

python 复制代码
# 类型修改
ndarray.astype(type)

6、序列化

python 复制代码
# ndarray序列化到本地
ndarray.tostring()

7、数组的去重

python 复制代码
np.unique(ndarray)

三、ndarray运算

1、逻辑运算

python 复制代码
# 逻辑运算
change > 0

# 布尔索引
change[change > 0]
python 复制代码
# 通用判断函数
np.all(change > 0)
np.any(change > 0)
python 复制代码
# 三元运算符
np.where(布尔值, True的位置的值, False的位置的值)
python 复制代码
# 逻辑或 逻辑与
np.logical_and(change > 0.5, change < 0.8)
np.logical_or()

2、统计运算

统计指标函数

min, max, mean, median, var, std

返回最大值、最小值所在位置

python 复制代码
np.argmax(temp, axis=)
np.argmin(temp, axis=)

3、数组与数的运算

python 复制代码
change * 10
change + 5

4、数组与数组的运算

广播机制

执行 broadcast 的前提在于,两个 ndarray 执行的是 element-wise 的运算,Broadcast机制的功能是为了方便不同形状的ndarray(numpy库的核心数据结构) 进行数学运算。

  1. 维度相等
  2. shape(其中相对应的一个地方为1)

5、矩阵运算

1)存储矩阵

  1. ndarray 二维数组
  2. matrix 数据结构
python 复制代码
d1 = np.array([[0, 1, 2], [3, 4, 5]]) 
d2 = np.mat([[0, 1, 2], [3, 4, 5]])

2)矩阵乘法

形状要求:(m, n) * (n, l) = (m, l)

python 复制代码
# 对于 ndarray 存储
np.matmul(d1, d3)
np.dot(d1, d3)
d1 @ d3
python 复制代码
# 对于 matrix 存储
d2 * d4

四、IO操作

1、Numpy读取

python 复制代码
np.genfromtxt("test.csv", delimiter=",")

2、缺失值的处理

1、直接删除含有缺失值的样本

2、替换/插补:按列求平均,用平均值进行填补

不如pandas好用!!

相关推荐
Juchecar1 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780511 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_1 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机8 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机9 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机9 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机9 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i9 小时前
drf初步梳理
python·django
每日AI新事件9 小时前
python的异步函数
python
这里有鱼汤10 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python