# -*- coding: utf-8 -*-
"""
主要记录代码,相关说明采用注释形势,供日常总结、查阅使用,不定时更新。
Created on Fri Aug 24 19:57:53 2018

@author: Dev
"""

import numpy as np
import random
 
# 常用函数
arr = np.arange(10)
print(np.sqrt(arr))    # 求平方根
print(np.exp(arr))    # 求e的次方
 
random.seed(200)    # 设置随机种子
x = np.random.normal(size=(8, 8))
y = np.random.normal(size=(8, 8))
np.maximum(x, y)    # 每一位上的最大值
 
arr = np.random.normal(size=(2, 4)) * 5
print(arr)
print(np.modf(arr))    # 将小数部分与整数部分分成两个单独的数组
 
# 向量化操作
# meshgrid的基本用法
points1 = np.arange(-5, 5, 1)     # [-5, 5]闭区间步长为1的10个点
points2 = np.arange(-4, 4, 1)
xs, ys = np.meshgrid(points1, points2)    # 返回一个由xs, ys构成的坐标矩阵
print(xs)   # points1作为行向量的len(points1) * len(points2)的矩阵
print(ys)   # points2作为列向量的len(points1) * len(points2)的矩阵
 
# 将坐标矩阵经过计算后生成灰度图
import matplotlib.pyplot as plt
points = np.arange(-5, 5, 0.01)     # 生成1000个点的数组
xs, ys = np.meshgrid(points, points)
z = np.sqrt(xs ** 2 + ys ** 2)  # 计算矩阵的平方和开根
print(z)
plt.imshow(z, cmap=plt.cm.gray)
plt.colorbar()
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")
plt.show()
 
 
# 将条件逻辑表达为数组运算
xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = np.array([True, False, True, True, False])
# 纯Python,用列表解析式做判断
result = [x if c else y for x, y, c in zip(xarr, yarr, cond)]
# zip()基本用法
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
for tupple_a in zip(a, b, c):   # python 3.x为了减少内存占用,每次zip()调用只返回一个元组对象
    print(tupple_a)
 
# np.where()
result = np.where(cond, xarr, yarr)
 
 
# np.where()的用法:
 
#np.where()的几个例子
# condition, x, y均指定
np.where([[False, True], [True, False]],
[[1, 2], [3, 4]],
[[9, 8], [7, 6]])
# 只指定condition时,返回np.nonzero(),即非零元素的索引
x = np.arange(9.).reshape(3, 3)
np.where( x > 5 )
x[np.where( x > 3.0 )]  # 将索引值带入原数组,得到满足大于3条件的元素
 
arr = np.random.normal(size=(4,4))
print(arr)
np.where(arr > 0, 2, -2)
np.where(arr > 0, 2, arr)   # 只将大于0的元素设置为2
 
# 用np.where()进行多条件判断
# 例子: 对0~100范围内的数进行判断
# 纯python
sum1 = 0
for i in range(0, 100):
    if np.sqrt(i) > 3 and np.sqrt(i) < 5:   # 平方根在(3, 5)之间
        sum1 += 3
    elif np.sqrt(i) > 3:    # 平方根在[5, 10)之间
        sum1 += 2
    elif np.sqrt(i) < 5:    # 平方根在(0, 3]之间
        sum1 += 1
    else:
        sum1 -= 1
print(sum1)
注: 这个例子其实用的不好,最后一个sum -= 1实际上没有用到,只是用这个例子说明多条件判断。
 
# 使用np.where()
num_list = np.arange(0, 100)
cond1 = np.sqrt(num_list) > 3
cond2 = np.sqrt(num_list) < 5
result = np.where(cond1 & cond2, 3, np.where(cond1, 2, np.where(cond2 < 5, 1, -1)))
print(sum(result))
 
 
# 数学与统计方法
arr = np.random.normal(size=(5, 4))
arr.mean()  # 平均值
np.mean(arr)
arr.sum()   # 求和
arr.mean(axis=1)    # 对行求平均值
arr.sum(0)  # 对每列求和
arr.sum(axis=0)
 
arr = np.arange(9).reshape(3, 3)
arr.cumsum(0)   # 每列的累计和
arr.cumprod(1) # 每行的累计积
 
注: 关于numpy中axis的问题
axis=1可理解为跨列操作
axis=0可理解为跨行操作
 
# 布尔型数组
arr = np.random.normal(size=(10, 10))
(arr > 0).sum() # 正值的数量
bools = np.array([False, False, True, False])
bools.any() # 有一个为True,则结果为True
bools.all() # 必须全为True,结果才为True
 
# 排序
arr = np.random.normal(size=(4, 4))
print(arr)
arr.sort()  # 对每行元素进行排序
 
arr = np.random.normal(size=(5, 3))
print(arr)
arr.sort(0) # 对每列元素进行排序
# 求25%分位数(排序后根据索引位置求得)
num_arr = np.random.normal(size=(1000, 1000))
num_arr.sort()
print(num_arr[0, int(0.25 * len(num_arr))])
 
# 求唯一值
names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
print(np.unique(names))
# 纯Python
print(sorted(set(names)))
# 判断values中的列表元素是否在数组list_a中
arr_a = np.array([6, 0, 0, 3, 2, 5, 6])
values = [2, 3, 6]
np.in1d(arr_a, values)
 
# 线性代数相关的函数
x = np.array([[1., 2., 3.], [4., 5., 6.]])
y = np.array([[6., 23.], [-1, 7], [8, 9]])
x.dot(y)    # 矩阵的乘法
np.dot(x, y)
np.dot(x, np.ones(3))
 
np.random.seed(12345)
from numpy.linalg import inv, qr
X = np.random.normal(size=(5, 5))
mat = X.T.dot(X)    # 矩阵X转置后再与原X相乘
inv(mat)    # 求逆矩阵
mat.dot(inv(mat))   # 与逆矩阵相乘
 
 
# 随机数
samples = np.random.normal(size=(4, 4))
samples
from random import normalvariate
# normalvariate(mu,sigma)
# mu: 均值
# sigma: 标准差
# mu = 0, sigma=1: 标准正态分布
 
# 比较纯Python与numpy生成指定数量的随机数的速度
N = 1000000    # 设置随机数的数量
get_ipython().magic(u'timeit samples = [normalvariate(0, 1) for _ in range(N)]')
get_ipython().magic(u'timeit np.random.normal(size=N)')
结果:
818 ms ± 9.87 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
34.5 ms ± 164 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
 
 
# 范例:随机漫步
import random
 
# 纯Python
position = 0
walk = [position]
steps = 1000
for i in range(steps):
    step = 1 if random.randint(0, 1) else -1
    position += step
    walk.append(position)
 
# np
np.random.seed(12345)
nsteps = 1000
draws = np.random.randint(0, 2, size=nsteps)    # 取不到2
steps = np.where(draws > 0, 1, -1)
walk = steps.cumsum()   # 求累计和
walk.min()
walk.max()
 
(np.abs(walk) >= 10).argmax()   # 首次到达10的索引数
 
# 一次模拟多个随机漫步
nwalks = 5000   # 一次生成5000组漫步数据
nsteps = 1000
draws = np.random.randint(0, 2, size=(nwalks, nsteps))
steps = np.where(draws > 0, 1, -1)
walks = steps.cumsum(1) # 将5000个样本中每一步的值进行累积求和
print(walks)
 
# 计算首次到达30
hits30 = (np.abs(walks) >= 30).any(1)   # 在列方向上进行对比
print(hits30)
print(hits30.sum()) # 到达+/-30的个数
# 查看每一步中首次到达30的步数
crossing_times = (np.abs(walks[hits30]) >= 30).argmax(1)
# 求到达30的平均步数
crossing_times.mean()
# 标准正态分布
steps = np.random.normal(loc=0, scale=0.25, size=(nwalks, nsteps))
 
 

numpy学习笔记 - numpy常用函数、向量化操作及基本数学统计方法的更多相关文章

  1. Python学习笔记之常用函数及说明

    Python学习笔记之常用函数及说明 俗话说"好记性不如烂笔头",老祖宗们几千年总结出来的东西还是有些道理的,所以,常用的东西也要记下来,不记不知道,一记吓一跳,乖乖,函数咋这么多 ...

  2. numpy学习笔记 - numpy数组的常见用法

    # -*- coding: utf-8 -*- """ 主要记录代码,相关说明采用注释形势,供日常总结.查阅使用,不定时更新. Created on Mon Aug 20 ...

  3. MySql cmd下的学习笔记 —— 有关常用函数的介绍(数学函数,聚合函数等等)

    (一)数学函数 abs(x)              返回x的绝对值 bin(x)               返回x的二进制(oct返回八进制,hex返回十六进制) ceiling(x)      ...

  4. Socket 学习笔记 01 常用函数

    常用方法 创建套接字: socket()    绑定本机端口: bind()    建立连接: connect(),accept()    侦听端口: listen()    数据传输: send() ...

  5. Java学习笔记——字符串常用函数

    class JavaTest4_String { public static void main(String[] args) { String str1 = "IOS,ANDROID,BB ...

  6. Numpy学习笔记(下篇)

    目录 Numpy学习笔记(下篇) 一.Numpy数组的合并与分割操作 1.合并操作 2.分割操作 二.Numpy中的矩阵运算 1.Universal Function 2.矩阵运算 3.向量和矩阵运算 ...

  7. Numpy学习笔记(上篇)

    目录 Numpy学习笔记(上篇) 一.Jupyter Notebook的基本使用 二.Jpuyter Notebook的魔法命令 1.%run 2.%timeit & %%timeit 3.% ...

  8. [学习笔记] Numpy基础 系统学习

    [学习笔记] Numpy基础 上专业选修<数据分析程序设计>课程,老师串讲了Numpy基础,边听边用jupyter敲了下--理解+笔记. 老师讲的很全很系统,有些点没有记录,在PPT里就不 ...

  9. NumPy学习笔记 三 股票价格

    NumPy学习笔记 三 股票价格 <NumPy学习笔记>系列将记录学习NumPy过程中的动手笔记,前期的参考书是<Python数据分析基础教程 NumPy学习指南>第二版.&l ...

随机推荐

  1. 算法22-----托普利茨矩阵leetcode766

    1.题目 如果一个矩阵的每一方向由左上到右下的对角线上具有相同元素,那么这个矩阵是托普利茨矩阵. 给定一个 M x N 的矩阵,当且仅当它是托普利茨矩阵时返回 True. 示例 1: 输入: matr ...

  2. why updating the Real DOM is slow, what is Virtaul DOM, and how updating Virtual DOM increase the performance?

    个人翻译: Updating a DOM is not slow, it is just like updating any JavaScript object; then what exactly ...

  3. [USACO07OPEN]Catch That Cow

    题目:洛谷P1588.HDU2717 题目大意:有一个人在点$n$,一头牛在点$k$,人每秒能从$x$移动到点$x+1$.$x-1$.$2x$,牛不会动,求最少多少秒后人能移动到牛所在的$k$. 思路 ...

  4. php中mysqli 处理查询结果集总结

    在PHP开发中,我们经常会与数据库打交道.我们都知道,一般的数据处理操作流程为 接收表单数据 数据入库 //连接数据库 $link = mysqli_connect("my_host&quo ...

  5. Vue系列(一):简介、起步、常用指令、事件和属性、模板、过滤器

    一. Vue.js简介 1. Vue.js是什么 Vue.js也称为Vue,读音/vju:/,类似view,错误读音v-u-e 是一个轻量级MVVM(Model-View-ViewModel)框架,和 ...

  6. 《你又怎么了我错了行了吧》第九次团队作业:Beta冲刺与验收准备

    项目 内容 这个作业属于哪个课程 软件工程 这个作业的要求在哪里 实验十三 团队作业9 团队名称 你又怎么了我错了行了吧 作业学习目标 (1)掌握软件黑盒测试技术: (2)学会编制软件项目总结PPT. ...

  7. 高级聚合函数rollup(),cube(),grouping sets()

       rollup(),cube(),grouping sets()   上面这几个函数,是对group by分组功能做的功能扩展. a.rollup()   功能:在原结果基础上追加一行总合计记录 ...

  8. 日志工具全面理解及配置应用---以Log4j例子

    一.日志系统基本常识 1.日志系统作用:将日志信息输出到控制台和文本文件,以追踪代码运行信息. 2.日志系统操作的是什么?日志系统打印信息,也是调用日志系统的log.Info(),log.Warn() ...

  9. [using_microsoft_infopath_2010]Chapter4 使用SharePoint列表表单

    本章概要: 1.把SharePoint列表表单转换成InfoPath可用形式 2.使用字段和控件 3.规划表单布局 4.理解列表表单的局限性

  10. [using_microsoft_infopath_2010]Chapter3 表单设计基础:使用InfoPath布局,控件,和视图

    本章概要 1.使用InfoPath的布局工具构建吸引人的表单 2.使用InfoPath表格工具 3.在表单上添加字段和控件 4.使用section和container组织表单里的控件 5.在一个表单上 ...