numpy是一个python和矩阵相关的库,在机器学习中非常有用,记录下numpy的基本用法

numpy的数组类叫做ndarray也叫做数组,跟python标准库中的array.array不同,后者只处理一维的数组而且提供很少的函数,numpy中有更多重要的属性

分别是

ndarray.ndim    该数组的维度,轴的数量

ndarray.shape    该数组的尺寸二维数组(m, n)m行n列,如果是三维或者以上的会包含其维度即(维度,m,n)

ndarray.size    数组中所有元素的数量

ndarray.dtype    数组中元素的类型

ndarray.itemsize 数组中每个元素的字节大小,float64中此项为64/8,int32中此项为32/8

ndarray.data    数组中包含的数据的缓冲区,一般不使用,都是使用索引来访问元素

数组的创建

np.array([2,3,4])

np.array([[2,3,4],[3,4,5]], dtype=np.int32)

np.zeros((3,4))创建一个全零的3*4数组

np.ones(3,4)创建一个全一的3*4数组

np.empty((2,3))创建一个数组,初始内容随机,取决内存的状态,默认创建的数组类型为float64

使用arange函数可以创建一个序列,类似于列表的数组

np.arange(10, 30, 5)从10到30以5为步长创建一个数组

如果不知道步长的话可以使用linspace

np.linspace(0,2,9)从0到2平均产生9个数

reshape函数可以将数组转换成指定维度,行,列的数组

np.arange(100).reshape(10,10)将一个一维的0-99的数组转换为10个0-9的数组

基础的操作

>>> a = np.array( [,,,] )
>>> b = np.arange( )
>>> b
array([, , , ])
>>> c = a-b
>>> c
array([, , , ])
>>> b**
array([, , , ])
>>> *np.sin(a)
array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854])
>>> a<
array([ True, True, False, False], dtype=bool)

两个矩阵相乘,使用dot函数,如果使用*结果是元素相应位置的元素相乘,不符合矩阵乘法

>>> A = np.array( [[,],
... [,]] )
>>> B = np.array( [[,],
... [,]] )
>>> A*B # elementwise product
array([[, ],
[, ]])
>>> A.dot(B) # matrix product
array([[, ],
[, ]])
>>> np.dot(A, B) # another matrix product
array([[, ],
[, ]])

使用+=或者*=会修改已经存在的数组而不是创建一个新的数组

sum函数计算数组总和

min函数求最小

max函数求最大

如果想求行中总和或者列中总和可以使用axis参数

sum(axis=0)求列总和,axis=1求行总和

max,min类似

>>> b = np.arange().reshape(,)
>>> b
array([[ , , , ],
[ , , , ],
[ , , , ]])
>>>
>>> b.sum(axis=) # sum of each column
array([, , , ])
>>>
>>> b.min(axis=) # min of each row
array([, , ])
>>>
>>> b.cumsum(axis=) # cumulative sum along each row
array([[ , , , ],
[ , , , ],
[ , , , ]])

numpy提供了常用的数学函数,sin,cos,exp等

一维数组可以被索引,切片,迭代,就像其他和列表一样的python序列一样

>>> a = np.arange()**
>>> a
array([ , , , , , , , , , ])
>>> a[] >>> a[:]
array([ , , ])
>>> a[::] = - # equivalent to a[::] = -; from start to position , exclusive, set every 2nd element to -
>>> a
array([-, , -, , -, , , , , ])
>>> a[ : :-] # reversed a
array([ , , , , , -, , -, , -])
>>> for i in a:
... print(i**(/.))
...
nan
1.0
nan
3.0
nan
5.0
6.0
7.0
8.0
9.0

多维数组每个轴有一个索引,这些索引以逗号分隔的元组给出

>>> def f(x,y):
... return *x+y
...
>>> b = np.fromfunction(f,(,),dtype=int)
>>> b
array([[ , , , ],
[, , , ],
[, , , ],
[, , , ],
[, , , ]])
>>> b[,] >>> b[:, ] # each row in the second column of b
array([ , , , , ])
>>> b[ : ,] # equivalent to the previous example
array([ , , , , ])
>>> b[:, : ] # each column in the second and third row of b
array([[, , , ],
[, , , ]])

当提供的索引数量少于轴(维)数,缺少的索引被当做完整的切片

b[-1]=b[-1, :]即取出最后一行的所有元素

对多维数组来说,迭代只迭代一个(轴)维度

>>> for row in b:
... print(row)
...
[ ]
[ ]
[ ]
[ ]
[ ]

如果要获取所有元素

>>> for element in b.flat:
... print(element)
...

连接不同的数组

np.vstack()添加到下一行

np.hstack()添加到同行尾部

>>> a = np.floor(*np.random.random((,)))
>>> a
array([[ ., .],
[ ., .]])
>>> b = np.floor(*np.random.random((,)))
>>> b
array([[ ., .],
[ ., .]])
>>> np.vstack((a,b))
array([[ ., .],
[ ., .],
[ ., .],
[ ., .]])
>>> np.hstack((a,b))
array([[ ., ., ., .],
[ ., ., ., .]])

分离数组元素

np.hsplit()

np.vsplit()

>>> a = np.floor(*np.random.random((,)))
>>> a
array([[ ., ., ., ., ., ., ., ., ., ., ., .],
[ ., ., ., ., ., ., ., ., ., ., ., .]])
>>> np.hsplit(a,) # Split a into
[array([[ ., ., ., .],
[ ., ., ., .]]), array([[ ., ., ., .],
[ ., ., ., .]]), array([[ ., ., ., .],
[ ., ., ., .]])]
>>> np.hsplit(a,(,)) # Split a after the third and the fourth column
[array([[ ., ., .],
[ ., ., .]]), array([[ .],
[ .]]), array([[ ., ., ., ., ., ., ., .],
[ ., ., ., ., ., ., ., .]])]

数组的复制和查看

当操作和操作数组时,他们的数据有时会被复制到一个新的数组中,这通常是初学者混淆的来源。有三种情况

>>> a = np.arange()
>>> b = a # no new object is created
>>> b is a # a and b are two names for the same ndarray object
True
>>> b.shape = , # changes the shape of a
>>> a.shape
(, )

赋值语句并不等于创建一个新的数组,而是对旧数组的引用

查看与浅拷贝

不同的数组对象可以享有相同的数据,view方法可以创建一个新的数组对象拥有相同的数据

>>> c = a.view()
>>> c is a
False
>>> c.base is a # c is a view of the data owned by a
True
>>> c.flags.owndata
False
>>>
>>> c.shape = , # a's shape doesn't change
>>> a.shape
(, )
>>> c[,] = # a's data changes
>>> a
array([[ , , , ],
[, , , ],
[ , , , ]])

对数组切片返回一个数组的view

>>> s = a[ : , :]     # spaces added for clarity; could also be written "s = a[:,1:3]"
>>> s[:] = # s[:] is a view of s. Note the difference between s= and s[:]=
>>> a
array([[ , , , ],
[, , , ],
[ , , , ]])

view和切片得到的数组如果改变,源数组也会改变

copy方法会复制完整的数据和其数据

>>> d = a.copy()                          # a new array object with new data is created
>>> d is a
False
>>> d.base is a # d doesn't share anything with a
False
>>> d[,] =
>>> a
array([[ , , , ],
[, , , ],
[ , , , ]])

参考自官方文档

https://docs.scipy.org/doc/numpy-dev/user/quickstart.html

python numpy学习记录的更多相关文章

  1. Python NumPy学习总结

    一.NumPy简介 其官网是:http://www.numpy.org/ NumPy是Python语言的一个扩充程序库.支持高级大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库.Num ...

  2. Python爬虫学习记录【内附代码、详细步骤】

    引言: 昨天在网易云课堂自学了<Python网络爬虫实战>,视频链接 老师讲的很清晰,跟着实践一遍就能掌握爬虫基础了,强烈推荐! 另外,在网上看到一位学友整理的课程记录,非常详细,可以优先 ...

  3. python爬虫学习记录

    爬虫基础 urllib,urllib2,re都是python自带的模块 urllib,urllib2区别是urllib2可以接受一个Request类的实例来设置url请求的headers,即可以模拟浏 ...

  4. python numpy 学习

    例子 >>> import numpy as np >>> a = np.arange(15).reshape(3, 5) >>> a array ...

  5. 简明 Python 教程--学习记录

    注意,我们在print语句的结尾使用了一个 逗号 来消除每个print语句自动打印的换行符.这样做有点难看,不过确实简单有效. print # prints a blank line 注意,没有返回值 ...

  6. python多线程学习记录

    1.多线程的创建 import threading t = t.theading.Thread(target, args--) t.SetDeamon(True)//设置为守护进程 t.start() ...

  7. Python numpy学习笔记(一)

    下边代码是关于numpy的一些基本用法,包括数组和矩阵操作等... import numpy as np print "<== print version ==>" p ...

  8. Python tkinter 学习记录(一) --label 与 button

    最简的形式 from tkinter import * root = Tk() # 创建一个Tk实例 root.wm_title("标题") # 修改标题 root.mainloo ...

  9. python爬虫学习记录——各种软件/库的安装

    Ubuntu18.04安装python3-pip 1.apt-get update更新源 2,ubuntu18.04默认安装了python3,但是pip没有安装,安装命令:apt install py ...

随机推荐

  1. Ta-Lib用法介绍 !

    一.函数索引 重叠研究 BBANDS Bollinger Bands DEMA Double Exponential Moving Average EMA Exponential Moving Ave ...

  2. PHP实现RESTful风格的API实例

    原生方式实现,直接撸代码 Request.php :包含一个Request类,即数据操作类.接收到URL的数据后,根据请求URL的方式(GET|POST|PUT|PATCH|DELETE)对数据进行相 ...

  3. AC日记——[ZJOI2015]幻想乡战略游戏 洛谷 P3345

    [ZJOI2015]幻想乡战略游戏 思路: 树剖暴力转移: 代码: #include <bits/stdc++.h> using namespace std; #define maxn 1 ...

  4. 【剑指offer】面试题 29. 顺时针打印矩阵

    面试题 29. 顺时针打印矩阵 题目描述 题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...

  5. 公司gitlab不支持ssh时,用http提交代码免密输入方法

    由于公司内网22端口被封,只能拨vpn 才能用ssh 提交代码.因此记录以下免密码http(https)提交方式. 修改项目下.git/config 将原来的 http://git.xxx.com/x ...

  6. Linux前后台进程切换

    (1).Linux前台进程与后台进程的区别 前台进程:是在终端中运行的命令,那么该终端就为进程的控制终端,一旦这个终端关闭,这个进程也随之消失. 后台进程:也叫守护进程(Daemon),是运行在后台的 ...

  7. RabbitMQ (九) 消息的参数详解

    上篇文章讲了声明一个队列时的参数设置,这篇文章主要说一说发布消息时的参数设置. 发布消息时的完整入参是这样的: channel.BasicPublish ( exchange: "test_ ...

  8. BZOJ 3809 Gty的二逼妹子序列(莫队+分块)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3809 [题目大意] 给定一个长度为n(1<=n<=100000)的正整数序 ...

  9. BZOJ 3399 [Usaco2009 Mar]Sand Castle城堡(贪心)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3399 [题目大意] 将一个集合调整成另一个集合中的数,把一个数+1需要消耗x,-1需要 ...

  10. 【带权并查集】Gym - 100923H - Por Costel and the Match

    裸题. 看之前的模版讲解吧,这里不再赘述了. #include<cstdio> #include<cstring> using namespace std; int fa[10 ...