01、python数据分析与机器学习实战——Python科学计算库-Numpy

NumPy介绍

NumPy系统是Python的一种开源的数值计算扩展。
这种工具可用来存储和处理大型矩阵,
比Python自身的嵌套列表(nested list structure)结构要高效的多
(该结构也可以用来表示矩阵(matrix))。

用numpy打开一个文件

假设有下面这么一个txt文件,要用numpy打开:

Year,WHO region,Country,Beverage Types,Display Value
1986,Western Pacific,Viet Nam,Wine,0
1986,Americas,Uruguay,Other,0.5
1985,Africa,Cte d'Ivoire,Wine,1.62
1986,Americas,Colombia,Beer,4.27
1987,Americas,Saint Kitts and Nevis,Beer,1.98
1987,Americas,Guatemala,Other,0
1987,Africa,Mauritius,Wine,0.13
1985,Africa,Angola,Spirits,0.39
1986,Americas,Antigua and Barbuda,Spirits,1.55
1984,Africa,Nigeria,Other,6.1
1987,Africa,Botswana,Wine,0.2
1989,Americas,Guatemala,Beer,0.62
1985,Western Pacific,Lao People's Democratic Republic,Beer,0
1984,Eastern Mediterranean,Afghanistan,Other,0
1985,Western Pacific,Viet Nam,Spirits,0.05
1987,Africa,Guinea-Bissau,Wine,0.07
1984,Americas,Costa Rica,Wine,0.06
1989,Africa,Seychelles,Beer,2.23
1984,Europe,Norway,Spirits,1.62
1984,Africa,Kenya,Beer,1.08
1986,South-East Asia,Myanmar,Wine,0
1989,Americas,Costa Rica,Spirits,4.51
1984,Europe,Romania,Spirits,2.67
1984,Europe,Turkey,Beer,0.44
1985,Africa,Comoros,Other,
1984,Eastern Mediterranean,Tunisia,Other,0
1985,Europe,United Kingdom of Great Britain and Northern Ireland,Wine,1.36
1984,Eastern Mediterranean,Bahrain,Beer,2.22
1987,Western Pacific,Viet Nam,Beer,0.11
1986,Europe,Italy,Other,
1986,Africa,Sierra Leone,Other,4.48
1986,Western Pacific,Micronesia (Federated States of),Wine,0
1989,Africa,Mauritius,Beer,1.6

……

import numpy

world_alcohol=numpy.genfromtxt("world_alcohol.txt",delimiter=",",dtype=str)
print(type(world_alcohol))
print(world_alcohol)

首先导入numpy库,然后用numpy.genfromtxt以“,”为分隔符将world_alcohol.txt文件导入;
然后用print(type(world_alcohol))打印world_alcohol的类型;
最后再将整个world_alcohol打印出来。
结果如下:
01、python数据分析与机器学习实战——Python科学计算库-Numpy
补充一点:如果不知道某个方法的作用,可以打印help语句来获取,比如:

print(help(numpy.genfromtxt))

它会打印出帮助注释:

01、python数据分析与机器学习实战——Python科学计算库-Numpy

numpy基础

import numpy

vector=numpy.array([5,10,15,20])
matrix=numpy.array([[5,10,15,20],[20,25,30],[35,40,45]])
print(vector)
print(matrix)

利用numpy的array可以创建矩阵:
01、python数据分析与机器学习实战——Python科学计算库-Numpy
通过.shape方法可以打印矩阵的属性:

import numpy

vector=numpy.array([1,2,3,4])
print(vector.shape)
matrix=numpy.array([[2,10,15],[20,25,30]])
print(matrix.shape)

01、python数据分析与机器学习实战——Python科学计算库-Numpy
第一行表示有四个元素,第二行表示这是一个2行3列的矩阵。通过.dtype方法可以打印元素的类型:

import numpy

numbers=numpy.array([1,2,3,4])
print(numbers)
print(numbers.dtype)

01、python数据分析与机器学习实战——Python科学计算库-Numpy
如果想要从矩阵中提取相应的元素,可以直接用索引,以打开的上述txt文件为例:

import numpy

world_alcohol=numpy.genfromtxt("world_alcohol.txt",delimiter=",",dtype=str,skip_header=1)
print(world_alcohol)
uruguay_other_1986=world_alcohol[1,4]
third_country=world_alcohol[2,2]
print(uruguay_other_1986)
print(third_country)

01、python数据分析与机器学习实战——Python科学计算库-Numpy
numpy同样也提供了切片的操作:

import numpy

vector=numpy.array([5,10,15,20])
print(vector[0:3])
matrix=numpy.array([
[5,10,15],
[20,25,30],
[35,40,45]
])
print(matrix[:,1])
print(matrix[:,0:2])
print(matrix[1:3,0:2])

这里要注意的是:切片操作的时候可以用“:”代替一整行或者一整列以及从某行到某行和从某列到某列,还有,切片是不包含后面的参数内容的。
01、python数据分析与机器学习实战——Python科学计算库-Numpy
可以利用矩阵元素的值是否与给定的值相等打印bool值:

import numpy

vector=numpy.array([5,10,15,20])
print(vector==10)

matrix=numpy.array([
[5,10,15],
[20,25,30],
[35,40,45]
])
print(matrix==25)

01、python数据分析与机器学习实战——Python科学计算库-Numpy
然后可以将获得的bool值作为索引带回到矩阵中,同时判断是否相等同样支持逻辑运算:

import numpy

vector=numpy.array([5,10,15,20])
equal_to_ten=(vector==10)
print(equal_to_ten)
print(vector[equal_to_ten])

matrix=numpy.array([
[5,10,15],
[20,25,30],
[35,40,45]
])
second_column_25=(matrix[:,1]==25)
print(second_column_25)
print(matrix[second_column_25,:])
matrix[second_column_25,1]=10
print(matrix)

equal_to_ten_and_five=(vector==10)&(vector==5)
print(equal_to_ten_and_five)

equal_to_ten_or_five=(vector==10)|(vector==5)
print(equal_to_ten_or_five)

01、python数据分析与机器学习实战——Python科学计算库-Numpy
可以利用.astype方法改变矩阵元素的类型:

import numpy

vector=numpy.array(["1","2","3"])
print(vector.dtype)
print(vector)
vector=vector.astype(float)
print(vector.dtype)
print(vector)

01、python数据分析与机器学习实战——Python科学计算库-Numpynumpy也提供了求最值和求和的方法:

import numpy

vector=numpy.array([5,10,15,20])
print(vector.min())

matrix=numpy.array([
[5,10,15],
[20,25,30],
[35,40,45]
])
print(matrix.sum(axis=1))
print(matrix.sum(axis=0))

sum中的参数:axis=1表示对行求和,axis=0表示对列求和
01、python数据分析与机器学习实战——Python科学计算库-Numpy

numpy也提供了一些很便利的方法:

np.arange(15)

生成从0到14共15个数字:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

a=np.arange(15).reshape(3,5)

将向量转换为矩阵的操作:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

print(a.shape) 
print(a.ndim) 
print(a.dtype.name) 
print(a.size)

分别打印矩阵的属性、维度、元素类型名、元素数量:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

print(np.zeros((3,4)))
print(np.ones((2,3,4),dtype=np.int32))

创建一个元素全为0,2行3列的矩阵和元素全为1,3维3行4列的矩阵:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

print(np.arange(10,30,5))
print(np.arange(0,2,0.3))

指定起点、终点和步长,打印向量:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

print(np.random.random((2,3)))

生成一个2行3列的随机数矩阵:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

import numpy as np

print(np.arange(15))
a=np.arange(15).reshape(3,5)
print(a)
print(a.shape)
print(a.ndim)
print(a.dtype.name)
print(a.size)

print(np.zeros((3,4)))
print(np.ones((2,3,4),dtype=np.int32))

print(np.arange(10,30,5))
print(np.arange(0,2,0.3))

print(np.arange(12).reshape(4,3))
print(np.random.random((2,3)))

numpy中也提供了一些常量:

import numpy as np
from numpy import pi

print(np.linspace(0,2*pi,100))

生成从0到2π的100个数:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

import numpy as np

B=np.arange(3)
print(B)
print(np.exp(B))
print(np.sqrt(B))

开方运算和e的次方运算:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

a=np.array([20,30,40,50])
b=np.arange(4)
print(a)
print(b)
c=a-b
print(c)
c=c-1
print(c)
b**2
print(b**2)
print(a<35)

进行矩阵之间的四则运算和乘方运算、逻辑运算:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

A=np.array([
    [1,1],
    [0,1]
])
B=np.array([
    [2,0],
    [3,4]
])
print(A)
print('--------')
print(B)
print('--------')
print(A*B)
print('--------')
print(A.dot(B))
print('--------')
print(np.dot(A,B))

还有矩阵运算:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

a=np.floor(10*np.random.random((3,4)))
print(a)
print('-------')
print(a.ravel())

将矩阵转换为向量:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

print('-------')
a.shape=(6,2)
print(a)
print('-------')
print(a.T)

print(a.reshape(3,-1))

然后再转换成另一种属性的矩阵,还可以转置和自定义行列:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

import numpy as np

a=np.floor(10*np.random.random((2,2)))
b=np.floor(10*np.random.random((2,2)))
print(a)
print(b)
print(np.hstack((a,b)))
print(np.vstack((a,b)))

矩阵的横竖拼接:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

import numpy as np

a=np.floor(10*np.random.random((2,12)))
print(a)
print(np.hsplit(a,3))
print(np.hsplit(a,(3,4)))

矩阵的横向平均拆分和指定拆分:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

a=np.floor(10*np.random.random((12,2)))
print(a)
print(np.vsplit(a,3))

矩阵的竖向拆分:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

import numpy as np

a=np.arange(12)
b=a
print(b is a )
b.shape=3,4
print(a.shape)
print(id(a))
print(id(b))

c=a.view()
print(c is a)
c.shape=2,6
print(a.shape)
c[0,4]=1234
print(a)
print(id(a))
print(id(c))

d=a.copy()
print(d is a)
d[0,0]=9999
print(a)
print(d)

矩阵的几种复制:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

import numpy as np

data=np.sin(np.arange(20)).reshape(5,4)
print(data)
ind=data.argmax(axis=0)
print(ind)
data_max=data[ind,range(data.shape[1])]
print(data_max)

矩阵竖向找最大值索引并将其打印出来:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

a=np.arange(0,40,10)
print(a)
b=np.tile(a,(2,3))
print(b)

矩阵的成倍扩大:
01、python数据分析与机器学习实战——Python科学计算库-Numpy

import numpy as np

a=np.array([[4,3,5],[1,2,1]])
print(a)
b=np.sort(a,axis=1)
print(b)
a.sort(axis=0)
print(a)
a=np.array([4,3,1,2])
j=np.argsort(a)
print(j)
print(a[j])

矩阵的横向排序、竖向排序和递增索引排序:
01、python数据分析与机器学习实战——Python科学计算库-Numpy