numpy.mean
np.mean(data,axis=0)
np.mean(data,axis=1)
- 此处
data
是二维数组,axis=0
输出一行,表示求每一列的均值,axis=1
输出的是一列,表示求每一行的均值
np.std
- 此函数用于求标准差
np.std(data,axis=0)
np.std(data,axis=1)
data
为二维数组,axis=0
求每一列的标准差,输出为一行;axis=1
求每一行的标准差。输出为一列。
np.where
- 返回一组索引值
- 如果是一维数组,则返回一维索引
>>> a=np.random.randint(10,100,size=(8))
>>> a
array([24, 84, 24, 75, 48, 76, 69, 68])
>>> np.where(a>30)
(array([1, 3, 4, 5, 6, 7], dtype=int64),)
- 如果是二维数组,则返回的类型如下,第一个数组标识x坐标,第二个数组表示y坐标
a = np.arange(8)
a
array([0, 1, 2, 3, 4, 9, 10, 17])
np.where(a>4)
(array([5, 6, 7], dtype=int64),)
np.random.randint
- 用来生产一定范围内的整数如下例子所示
low
和high
表示范围,size
表示数组的形状
np.random.randint(low=10,high=100,size=(4,4))
np.random.choice
- 下面的代码什么意思呢:就是在
0-99
的范围内,随机选8
个数出来
>>> import numpy as np
>>> np.random.choice(100,8)
array([82, 83, 99, 89, 69, 42, 67, 30])
>>>
np.divide
np.divide(x,y)
,如果x,y
维数相同,则是对应位置做除法,如果y
是一个数,x
中所有元素除以y
>>> dataset=[1,2,3,4,5]
>>> data_std=[2,2,2,2,2]
>>> np.divide(dataset,data_std)
array([0.5, 1. , 1.5, 2. , 2.5])
numpy数组的切片操作
- 对于数组
arr[a][b][c]
,arr[:,-1,:]
其中,
号表示一维,此处的意思在a
个b*c
的数组中,选择每个数组的最后一行,形成一个a*c
的数组。
>>> a=np.random.randint(1,100,size=(3,3,3))
>>> a
array([[[85, 43, 85],
[47, 18, 61],
[73, 96, 25]],
[[40, 61, 40],
[73, 74, 37],
[65, 91, 43]],
[[33, 54, 42],
[96, 97, 98],
[ 5, 63, 41]]])
>>> a[:,-1,:]
array([[73, 96, 25],
[65, 91, 43],
[ 5, 63, 41]])
切片操作2
- 此处的切片可以看出是对三维的数组中,后两维度的矩阵,用后一行减去前一行。
>>> a=np.random.randint(1,100,size=(3,4,5))
>>> c=np.zeros_like(a)
>>> a
array([[[12, 91, 27, 31, 27],
[65, 83, 78, 54, 3],
[38, 5, 95, 58, 5],
[79, 16, 89, 3, 22]],
[[44, 13, 40, 85, 39],
[ 6, 15, 51, 89, 18],
[41, 65, 20, 35, 10],
[ 7, 69, 73, 34, 24]],
[[65, 35, 10, 54, 63],
[93, 23, 4, 56, 41],
[45, 44, 85, 40, 87],
[11, 43, 26, 19, 73]]])
>>> c[:,1:,:]=a[:,1:,:]-a[:,:-1,:]
>>> c
array([[[ 0, 0, 0, 0, 0],
[ 53, -8, 51, 23, -24],
[-27, -78, 17, 4, 2],
[ 41, 11, -6, -55, 17]],
[[ 0, 0, 0, 0, 0],
[-38, 2, 11, 4, -21],
[ 35, 50, -31, -54, -8],
[-34, 4, 53, -1, 14]],
[[ 0, 0, 0, 0, 0],
[ 28, -12, -6, 2, -22],
[-48, 21, 81, -16, 46],
[-34, -1, -59, -21, -14]]])
>>>
np.where
python
中判断0为False
,非0为True
,所以,np.where
返回的就是为真的元素- 返回结果是一个
tuple
类型,长度为2,第一维表示行坐标,第二个表示列坐标
>>> a
array([[0., 1., 1., 1., 1.],
[1., 0., 1., 1., 1.],
[1., 1., 0., 1., 1.],
[1., 1., 1., 0., 1.],
[1., 1., 1., 1., 0.]])
>>> np.where(a)
(array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4],
dtype=int64), array([1, 2, 3, 4, 0, 2, 3, 4, 0, 1, 3, 4, 0, 1, 2, 4, 0, 1, 2, 3],
dtype=int64))
>>>
np.eye()
- 返回一个对角线为
1
,其余部分为0的数组
>>> c=np.eye(5,5)
>>> c
array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
>>>
np.identity()
- 与
np.eye
相似,但是,只能创建方阵
>>> a=np.identity(5)
>>> a
array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])