1. 为什么要学习numpy?


  • numpy可以对整个array进行复杂计算,而不需要像list一样写loop
  • 它的ndarray提供了快速的基于array的数值运算
  • memory-efficient container that provides fast numerical operations
  • 学习pandas的必备

证明numpy比list优秀:

import numpy as np
my_arr = np.arange(1000000)
my_list = list(range(1000000)) %time for _ in range(10): my_arr2 = my_arr * 2 # Wall time: 25 ms
%time for _ in range(10): my_list2 = [x * 2 for x in my_list] # Wall time: 933 ms

2. Numpy基本用法


2.1. 创建np.ndarry

注意: numpy只能装同类型的数据

# Method 1: np.array()
## 1-D
a = np.array([1,2,3])
a.shape
a.dtype # int32, boolean, string, float
a.ndim ## 2-D
a = np.array([[0,1,2],[3,4,5]]) # Method 2:使用函数(arange, linspace, ones, zeros, eys, diag,random)创建
a = np.arange(10)
a = np.linspace(0,1,6, endpoint=False)
a = np.ones((3,3))
a = np.zeros((3,3))
a = np.eye(3)
a = np.diag(np.array([1,2,3,4]))
a = np.triu(np.ones((3,3)),1) # Method 3: Random values
a = np.random.rand(4) # unifomr in [0,1]
a = np.random.randn(4) # Gaussian
np.random.seed(1234)

2.2. Indexing and Slicing

  • Slice create a view on the original array(change will affect original array)
# 1-D
a = np.arange(10)
a[5], a[-1] # Index: 4,9
a[5:8] = 12 # Slice: all 5-8 is set as 12
arr[5:8].copy() # Slice without view # 2-D
a = np.ones((3,3))
a[2] # second row
a[2].copy() # slice without view
a[0][2] # special value a[:2]
a[:2, 1:] = 0

Boolean Index

names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
data = np.random.randn(7, 4) data[names == 'Bob'] # select a row from data based on the if names equals Bob(boolean value)
data[~(names == 'Bob')] # not equal to Bob
data[(names == 'Bob') | (names == 'Will')] #e qual to Bob and Will
data[data<0] = 0

2.3. Universal Functions

a function that performs element-wise operations on data in ndarrays

a = np.arange(10)
b = np.arange(2,12) # single
a + 1
a*2
np.sqrt(a)
np.exp(a)
np.sin(a) # binary
a>b # return boolean ndarray
np.array_equal(a,b) # eual?
np.maximum(a, b) # find max value between each pair values
np.logical_or(a,b) # Attentions, a and b must be boolean array

2.4. Array-oriented

  • Probelm 1

we wished to evaluate the function `sqrt(x^2 + y^2)`` across a regular grid of values.

The np.meshgrid function takes two 1D arrays and produces two 2D matrices corresponding to all pairs of (x, y) in the two arrays:

points = np.arange(-5, 5, 0.01) # 1000 equally spaced points
xs, ys = np.meshgrid(points, points)
z = np.sqrt(xs ** 2 + ys ** 2) import matplotlib.pyplot as plt
%matplotlib inline plt.imshow(z, cmap=plt.cm.gray); plt.colorbar()
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")

  • Problem 2

we have two array(x,y) and one boolean array, we want select x if boolean=True, while select y if boolean=False->np.where()

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])
result = np.where(cond, xarr, yarr) # array([1.1, 2.2, 1.3, 1.4, 2.5])

np.where的后面两个参数可以是array,数字. 是数字的话就可以做替换工作,比如我们将随机生成的array中大于0的替换为2,小于0的替换为-2

arr = np.random.randn(4, 4)
np.where(arr > 0, 2, -2) # 大于0改为2,小于0改为-2
np.where(arr > 0, 2, arr) # 大于0改为2,小于0不变

2.5. Mathematical Operations

a = np.random.randn(5, 4)
np.mean(a)
np.mean(a, axis = 1)
np.sum(a)
a.consum()
a.sort()
a.argmax() # index of maxium names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
np.unique(names)
sorted(set(names))



Python Numpy-基础教程的更多相关文章

  1. Python Numpy基础教程

    Python Numpy基础教程 本文是一个关于Python numpy的基础学习教程,其中,Python版本为Python 3.x 什么是Numpy Numpy = Numerical + Pyth ...

  2. Python数据分析基础教程

    Python数据分析基础教程(第2版)(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/1_FsReTBCaL_PzKhM0o6l0g 提取码:nkhw 复制这段内容后 ...

  3. Python机器学习基础教程-第2章-监督学习之决策树集成

    前言 本系列教程基本就是摘抄<Python机器学习基础教程>中的例子内容. 为了便于跟踪和学习,本系列教程在Github上提供了jupyter notebook 版本: Github仓库: ...

  4. Python机器学习基础教程-第2章-监督学习之决策树

    前言 本系列教程基本就是摘抄<Python机器学习基础教程>中的例子内容. 为了便于跟踪和学习,本系列教程在Github上提供了jupyter notebook 版本: Github仓库: ...

  5. Python机器学习基础教程-第2章-监督学习之线性模型

    前言 本系列教程基本就是摘抄<Python机器学习基础教程>中的例子内容. 为了便于跟踪和学习,本系列教程在Github上提供了jupyter notebook 版本: Github仓库: ...

  6. Python机器学习基础教程-第2章-监督学习之K近邻

    前言 本系列教程基本就是摘抄<Python机器学习基础教程>中的例子内容. 为了便于跟踪和学习,本系列教程在Github上提供了jupyter notebook 版本: Github仓库: ...

  7. Python机器学习基础教程-第1章-鸢尾花的例子KNN

    前言 本系列教程基本就是摘抄<Python机器学习基础教程>中的例子内容. 为了便于跟踪和学习,本系列教程在Github上提供了jupyter notebook 版本: Github仓库: ...

  8. 小白必看Python视频基础教程

    Python的排名从去年开始就借助人工智能持续上升,现在它已经成为了第一名.Python的火热,也带动了工程师们的就业热.可能你也想通过学习加入这个炙手可热的行业,可以看看Python视频基础教程,小 ...

  9. Python机器学习基础教程

    介绍 本系列教程基本就是搬运<Python机器学习基础教程>里面的实例. Github仓库 使用 jupyternote book 是一个很好的快速构建代码的选择,本系列教程都能在我的Gi ...

  10. Python 3基础教程1-环境安装和运行环境

    本系列开始介绍Python3的基础教程,为什么要选中Python 3呢?之前呢,学Python 2,看过笨方法学Python,学了不到一个礼拜,就开始用Python写Selenium脚本.最近看到一些 ...

随机推荐

  1. NLP入门(三)词形还原(Lemmatization)

      词形还原(Lemmatization)是文本预处理中的重要部分,与词干提取(stemming)很相似.   简单说来,词形还原就是去掉单词的词缀,提取单词的主干部分,通常提取后的单词会是字典中的单 ...

  2. Webapi--Webapi 跨域链接

    1]创建 WebAPIWebAPI WebAPI,新建 ,新建 ->项目 ->ASP.NET Web >ASP.NET Web >ASP.NET Web >ASP.NET ...

  3. Pyinstaller如何将资源文件一起打包至exe中

    基本原理:Pyinstaller 可以将资源文件一起bundle到exe中,当exe在运行时,会生成一个临时文件夹,程序可通过sys._MEIPASS访问临时文件夹中的资源 官方说明:https:// ...

  4. [日常] nginx与负载均衡策略

    upstream mail.sina.net { #upstream的负载均衡,weight是权重,可以根据机器配置定义权重.weigth参数表示权值,权值越高被分配到的几率越大. server we ...

  5. 最长滑道问题(非递归,C++)

    这是爱奇艺的一道算法题. 题目描述请参考博客http://blog.csdn.net/sinat_30186009/article/details/52356053,在此表示感谢. 基本思路参考了以上 ...

  6. (5)Microsoft office Word 2013版本操作入门_标尺

    1.标尺 :左缩进,右缩进,悬挂缩进,首行缩进,阴影部分 可以左右拖拽调整边缘. 1.1  左缩进:默认缩进所在的段落,要缩进多段则需要多段落选中, 后拖动左缩进. 1.2 首行缩进缩进或者突出所选的 ...

  7. Hibernate入门(七)一对多入门案例

    一对多 场景模拟:用户(一)对订单(多) 1.建表 创建客户表,字段有:客户id,客户姓名,客户性别,客户年龄,客户年纪,客户电话. 创建订单表,字段有:订单编号,明细编号,客户编号(外键) DROP ...

  8. mediainfo使用

    1.linux安装mediainfo     yum  install  mediainfo(epel源安装) 2.输出文件信息到xml文件 mediainfo --OUTPUT=XML -f ftp ...

  9. java使用POI将数据导出放入Excel

    本文主要是将数据库取出的数据按照自定义的行列格式导出到excel中,POI则是实现我们需求所用到的技术. POI介绍 使用spring boot导入相关依赖 获取数据(自行处理) 完整代码实例:创建e ...

  10. C#DataTable复制、C#DataTable列复制、C#DataTable字段复制

    try { //获取满足条件的数据 DataTable Mdr = datable.Select().ToString("yyyy-MM-dd HH:mm:ss") + " ...