Numpy库
对Numpy库实在太不了解啦,利用这几天假期抓紧学习下Numpy相关知识
学习Numpy的原因是,这可以显著提高运算速度
a = np.random.normal(0, 2, 10000000)
begin = time.time()
np.sum(a)
end = time.time()
print(end-begin)
a = list(a)
begin = time.time()
sum(a)
end = time.time()
print(end-begin)
0.017951250076293945
0.6771886348724365
numpy库中最核心的数据结构就是n维数组(nd-array),每个n维度数组只能有一种元素(dtype属性中记录了)
numpy的数组的shape由一个多维元组来指定,一般不支持修改
一、数组创建
属性 | 作用 |
---|---|
a.shape | 返回一个元组,表明各个维度的元素 |
a.dtype | 返回数据类型 |
a.size | 返回元素的分数 |
函数 | 作用 |
---|---|
np.array(dtype=) | 转化list为nparray |
使用:
np.array([1,2,3],dtype= int64)
a = np.array([[1],[2],[3]],dtype=“float64”)
函数 | 作用 |
---|---|
np.zeros(tuple) | 全为0的数组 |
np.ones(tuple) | 全为1的数组 |
np.arange(tuple) | 类似于range方法 |
a.reshape(tuple) | 重构a,变为一个数组 |
二、基本操作
可以直接把算数操作作用在数组上
例如
a = np.arange(4).reshape((2,2,1,1))
print(a)
print(np.sin(a))
print(a**2)
print(a+4)
矩阵相乘用的方法是
函数 | 作用 |
---|---|
np.dot(A,B) | A, B相乘 |
通用函数
函数 | 作用 |
---|---|
np.sin(a) | 对a的每个元素都作用一下sin函数 |
np.cos(a) | 对a的每个元素都作用一下cos函数 |
np.sqrt(a) | 对a的每个元素都作用一下sqrt函数 |
np.log(a) | 对a的每个元素都作用一下log函数 |
聚合函数
函数 | 作用 |
---|---|
a.max() | 对a的每个元素都作用一下sin函数 |
a. min() | 对a的每个元素都作用一下cos函数 |
a.mean() | 对a的每个元素都作用一下sqrt函数 |
a.std() | 对a的每个元素都作用一下log函数 |
也可通过np.max()、np.sum()、np.std()来调用
a = np.arange(4).reshape((2,2,1,1))
print(np.max(a))
print(a.max())
print(np.min(a))
print(a.min())
print(np.sum(a))
print(a.sum())
三、索引方法
a = np.arange(100).reshape((10, 10))
print(a[:,2:5]) #选中所有行和第2,3,4,5列
print(a[[1,3,9],:][:, [2,7]]) #选中第1,3,9行和第2,7列
print(a[[1,3,9],[2,7]]) #出错!
四、布尔数组
希望在一个数组中找到所有的偶数
A [ A % 2 == 0]
具体的说:A 作为一个numpy数组,中间填上一个bool表达式,之后即可得到一个一维数组。原理是 A%2 == 0实际上得到了一个布尔数组,布尔数组作用在A上
利用这个可以选出符合条件的元素
np.where(condition, x, y)
condition就是一个布尔数组
import numpy as np
a = np.arange(12).reshape((3,4))
a = np.where(a>6, 1, 0)
print(a)
[[0 0 0 0]
[0 0 0 1]
[1 1 1 1]]
a = np.random.normal(0, 2, 10000000)
begin = time.time()
aa = a[a % 3 == 1]
end = time.time()
print(end-begin)
a = list(a)
begin = time.time()
aaa = np.array([i for i in a if i%3 == 1])
end = time.time()
print(end-begin)
0.29662632942199707
8.396028757095337
可见同样的算法,实现方式不同,速度上差太远了
五、数组操作
传统的数组操作是:
转成list,之后append
现在我们可以使用:
np.hstack() //horizontal append
data, target = sk.load_breast_cancer().data, sk.load_breast_cancer().target
target = target.reshape((len(target), 1))
print(np.hstack((data,target)))
相应的,还有np.vstack() // vertical append
六、视图
注意,这里的数组也是一个对象。注意需要深拷贝。