array:
import numpy as np # 载入numpy,缩写成np
>>> np.__version__
'1.14.4'
python 中list特点:
>>> lst=[1,2,3,4,5] # 列表本身对元素类型没有限制,但是这也会使运算变慢
>>> lst[2]
3
>>> lst[2]=10
>>> lst
[1, 2, 10, 4, 5]
>>> lst[2]=6.6
>>> lst
[1, 2, 6.6, 4, 5]
>>> lst='hard'
import array
>>> arr=array.array('i',[i for i in range(10)]) # typecode='i',限定类型只能是int,但是会使得效率更高
>>> arr
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> arr[5]
5
>>> arr[5]=6.6 # 故会报错
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>
arr[5]=6.6
TypeError: integer argument expected, got float
np.array创建数组:
>>> c=np.array([[1,2],[2,3]]) # 创建二维数组
>>> c.ndim
2
>>> c
array([[1, 2],
[2, 3]])
>>> d=np.array([[1], # 2X1矩阵
[2]])
>>> d
array([[1],
[2]])
[2]])
>>> d
array([[1],
[2]])
>>> arr=np.array(i for i in range(10)) #object 需要用中括号括起来
>>> arr
array(<generator object <genexpr> at 0x000001F1F01D55C8>, dtype=object)
>>> arr=np.array([i for i in range(10)])
>>> arr array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> ar=np.array([i for i in lst])
>>> ar # 长得不太一样,但是reshape后一样
ar是二维数组,所以有两个中括号,arr是一维数组
,array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> ar.reshape(2,-1) # -1,表示不考虑列,系统自动匹配
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> ar.reshape(2,-1) # -1,表示不考虑列,系统自动匹配
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> arr.reshape(2,-1)
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> if arr.any()==ar.any():
print('true')
else:
print('False')
# 验证后发现两者是一样的
true
>>> arr.dtype
dtype('int32')
>>> ar.dtype
dtype('int32')
>>> arr[3]
3
>>> arr[3]=4.3 #尝试改变元素,但是输出没有变化,系统会自动转化为int 类型
>>> arr
array([0, 1, 2, 4, 4, 5, 6, 7, 8, 9])
>>> arr.dtype
dtype('int32')
实际中用到的数据大多是浮点型:
>>> ar1=np.array([1,2,3.14])
>>> ar1.dtype
dtype('float64')
array.reshape(shape,order='C'):
or reshape(array,newshape,order='C')
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.reshape(2,-1)
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> a.reshape(2,5)
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> a.reshape(shape=(2,5)) # 搞不懂
Traceback (most recent call last):
File "<pyshell#400>", line 1, in <module>
a.reshape(shape=(2,5))
TypeError: 'shape' is an invalid keyword argument for this function
Traceback (most recent call last):
File "<pyshell#400>", line 1, in <module>
a.reshape(shape=(2,5))
TypeError: 'shape' is an invalid keyword argument for this function
>>> np.reshape(a,newshape=(2,-1),order='C')
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
reshape用来对数组的形状改变。-1表示不对行或者列考虑,由计算机匹配。
数据类型只能在定义时设定
dtype 即data type 的简写
其他创建np.array的方法:
全零np.zeros(shape=(x,y),dtype=float,order='C'):
>>> np.zeros(10)
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> np.zeros(shape=(2,5),dtype=int) # 两种方法转变成2维数组
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
>>> np.zeros(10).reshape(2,-1)
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
全一np.ones(shape=(x,y),dtype=None,order='C'):
>>> np.ones(shape=(2,4))
array([[1., 1., 1., 1.],
[1., 1., 1., 1.]])
>>> np.ones(shape=(2,4),dtype=None) # dtype默认为None
array([[1., 1., 1., 1.],
[1., 1., 1., 1.]])
>>> np.ones((3,5),dtype=int)
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
np.full(shape=(x,y),fill_value,dtype=None,order='C'):
# 格式 np.full(shape=(2,5),fill_value,dtype=None,order='C')
>>> np.full(shape=(2,5),fill_value=6,dtype=None,order='C')
array([[6, 6, 6, 6, 6],
[6, 6, 6, 6, 6]])
# full 不同于 ones 和zeros.默认ones和 zeros 的 dtype 是float
np.arange([start,]stop[,step]):
>>> l=[i for i in range(0,10,1)] # range的步距不能为浮点数
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls=np.arange(start=0,stop=10,step=0.4) # np.arange 的步长可以为小数
>>> ls
array([0. , 0.4, 0.8, 1.2, 1.6, 2. , 2.4, 2.8, 3.2, 3.6, 4. , 4.4, 4.8,
5.2, 5.6, 6. , 6.4, 6.8, 7.2, 7.6, 8. , 8.4, 8.8, 9.2, 9.6])
np.linspace:
>>> np.linspace(0,10,20) # 生成20个等间隔的数,包括stop=20在内
array([ 0. , 0.52631579, 1.05263158, 1.57894737, 2.10526316,
2.63157895, 3.15789474, 3.68421053, 4.21052632, 4.73684211,
5.26315789, 5.78947368, 6.31578947, 6.84210526, 7.36842105,
7.89473684, 8.42105263, 8.94736842, 9.47368421, 10. ])
>>> np.linspace(0,10,21) # 生成21个数才正好
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ,
5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5, 10. ])
random:
>>> import random
>>> random.randint(a=1,b=2) #在range(a,b)中随机选择一个整数
2
>>> random.random() #从0-1中选取一个随机数
0.8079806083153137
>>> random.choice(lst) # 随机从lst中选择一个数
4
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
np.random(可以用于生成矩阵):
np.random.random(sample_size=1)
生成sample_size 大小的服从均匀分布为Uniform(0, 1)的数组。
np.random.uniform(low, high, size)
生成服从均匀分布于Uniform(low, high)的size大小的数组。
np.random.normal(loc, scale, size)
生成服从N(loc, scale)大小为size的数组。
>>> np.random.randint(1,2,size=(2,4))
array([[1, 1, 1, 1],
[1, 1, 1, 1]])
>>> np.random.random(size=(2,4))
array([[0.86782819, 0.73717781, 0.35352435, 0.28328804],
[0.58428879, 0.13513095, 0.45413623, 0.67659482]])
>>> np.random.randint(1,4,size=(2,4))
array([[1, 1, 1, 1],
[3, 1, 3, 1]])
>>> np.random.choice(lst,size(2,4))
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
np.random.choice(lst,size(2,4))
NameError: name 'size' is not defined
>>> np.random.randint(0,10,size=10)
array([9, 5, 5, 9, 9, 1, 4, 5, 4, 8])
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
np.random.choice(lst,size(2,4))
NameError: name 'size' is not defined
>>> np.random.randint(0,10,size=10)
array([9, 5, 5, 9, 9, 1, 4, 5, 4, 8])
随机种子np.random.seed():
>>> np.random.seed(333)
>>> np.random.randint(1,4,size=(2,4))
array([[1, 1, 2, 3],
[3, 3, 1, 2]])
>>> np.random.seed(333)
>>> np.random.randint(1,4,size=(2,4))
array([[1, 1, 2, 3],
[3, 3, 1, 2]])
正态分布random.noramlvariate(mu,sigma),
np.random.normal(mu,sigma,size):
>>> random.normalvariate(0,1) # random 模块生成的正态分布数只有一个数字
1.9671020161041424
>>> np.random.normal(0,1,size=(2,4)) # np.random.normal 是可以生成矩阵,第一个为均值,第二个为方差
array([[-0.81058483, -1.36428529, 0.45644073, 0.08592951],
[ 2.2317828 , -0.54032917, 0.85372722, -1.70670445]])
>>> random.normalvariate(mu=0,sigma=1) # 第一个mu 是均值,sigma是方差
0.4691395238855669
基本属性:
>>> a=np.array([i for i in range(10)])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b=a.reshape(2,-1)
>>> b
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> a.ndim # a的维度
1
>>> b.ndim # b的维度
2
>>> a.shape
(10,)
>>> b.shape
(2, 5)
>>> a.size
10
>>> b.size
10
numpy.array 的数据访问:
>>> a[0] # 一维数组的访问,第一个元素
0
>>> b[0][0] # 二维数组的访问,第一个元素
0
>>> b[1,1] # 推荐方法,第二行第二列
6
>>> b[(1,1)]
6
>>> b[:3,:2] # 访问前3行,前两列
array([[0, 1],
[5, 6]])
>>> b[:1,:3] # 访问前一行前3列
array([[0, 1, 2]])
>>> b[:,:] # 访问所有行列的元素
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> b[:,2] # 访问所有行,第二列
array([2, 7])
>>> b[:,:2] # 所有行,前两列
array([[0, 1],
[5, 6]])
同样的:
>>> c
array([[3, 3, 7, 7, 1],
[0, 8, 2, 7, 0],
[1, 0, 8, 5, 3]])
>>> c[:2,1:] # 访问前两行,访问除第一列以外的列
array([[3, 7, 7, 1],
[8, 2, 7, 0]])
访问前两行,访问除第一列以外的列
array([[3, 7, 7, 1],
[8, 2, 7, 0]])
:前面默认是一,后面默认是最后。
# 访问前两行,对于列,希望每两个取一个
>>> c[:2,::2]
array([[3, 7, 1],
[0, 2, 0]])
每行元素倒着数,每列也倒着数
>>> c[::-1,::-1]
array([[3, 5, 8, 0, 1],
[0, 7, 2, 8, 0],
[1, 7, 7, 3, 3]])
降维处理:
>>> c[0] # 取出行号为0的列,也就是第一列
array([3, 3, 7, 7, 1])
>>> c[1]
array([0, 8, 2, 7, 0])
>>> c[0].ndim
1
子数组:
>>> subc=c[:2,1:] # 取前两行,后四列
>>> subc
array([[3, 7, 7, 1],
[8, 2, 7, 0]])
>>> subc[1,2] # 索引元素
7
>>> subc[1,2]=4 # 修改元素
>>> subc
array([[3, 7, 7, 1],
[8, 2, 4, 0]])
>>> c
array([[3, 3, 7, 7, 1],
[0, 8, 2, 4, 0],
[1, 0, 8, 5, 3]])
可以发现子数组中的元素改变,整个数组元素都会改变。
但是有时候不想这样。
可以用array.copy()函数:
>>> subc=c.copy()
>>> subc
array([[3, 3, 7, 7, 1],
[0, 8, 2, 4, 0],
[1, 0, 8, 5, 3]])
>>> subc[2,3]
5
>>> subc[2,3]=2
>>> subc
array([[3, 3, 7, 7, 1],
[0, 8, 2, 4, 0],
[1, 0, 8, 2, 3]])
>>> c
array([[3, 3, 7, 7, 1],
[0, 8, 2, 4, 0],
[1, 0, 8, 5, 3]])
2, 3]])
>>> c
array([[3, 3, 7, 7, 1],
[0, 8, 2, 4, 0],
[1, 0, 8, 5, 3]])
这里subx变了,但没有传递给c.
reshape:
>>> c.shape
(3, 5)
>>> c.reshape(2,-1) # 只关注行,不关注列,系统自动匹配。等效于(2,7.5),当然不存在
Traceback (most recent call last):
File "<pyshell#174>", line 1, in <module>
c.reshape(2,-1)
ValueError: cannot reshape array of size 15 into shape (2,newaxis)
>>> c.reshape(5,-1) # 等效于(5,3)
array([[3, 3, 7],
[7, 1, 0],
[8, 2, 4],
[0, 1, 0],
[8, 5, 3]])
Traceback (most recent call last):
File "<pyshell#174>", line 1, in <module>
c.reshape(2,-1)
ValueError: cannot reshape array of size 15 into shape (2,newaxis)
>>> c.reshape(5,-1) # 等效于(5,3)
array([[3, 3, 7],
[7, 1, 0],
[8, 2, 4],
[0, 1, 0],
[8, 5, 3]])
合并操作:
>>> np.concatenate([a1,a2,...],axis=0,out=None) # concatenate函数的格式
>>> x=np.array([1,2,3])
>>> y=np.array([3,2,1])
>>> np.concatenate([x,y],axis=0,out=None) # 合并
array([1, 2, 3, 3, 2, 1])
>>> np.concatenate([x,y],axis=1,out=None)
Traceback (most recent call last):
File "<pyshell#180>", line 1, in <module>
np.concatenate([x,y],axis=1,out=None)
numpy.core._internal.AxisError: axis 1 is out of bounds for array of dimension 1
Traceback (most recent call last):
File "<pyshell#180>", line 1, in <module>
np.concatenate([x,y],axis=1,out=None)
numpy.core._internal.AxisError: axis 1 is out of bounds for array of dimension 1
>> z=np.array([7,8,9])
>>> np.concatenate([x,y,z],axis=0,out=None) # 合并多个
array([1, 2, 3, 3, 2, 1, 7, 8, 9])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.reshape(2,-1)
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> np.concatenate([a.reshape(2,-1),a.reshape(2,-1)])
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
一维数组和二维数组合并(通过reshape把一维数组变成二维数组,然后再合并):
>>> b=np.array([i for i in range(2,7)])
>>> b
array([2, 3, 4, 5, 6])
>>> np.concatenate([a.reshape(2,-1),b])
Traceback (most recent call last):
File "<pyshell#193>", line 1, in <module>
np.concatenate([a.reshape(2,-1),b])
ValueError: all the input arrays must have same number of dimensions
>>> b.ndim # b的维度是一
1
>>> c=a.reshape(2,-1)
>>> c.ndim # c的维度是2
Traceback (most recent call last):
File "<pyshell#193>", line 1, in <module>
np.concatenate([a.reshape(2,-1),b])
ValueError: all the input arrays must have same number of dimensions
>>> b.ndim # b的维度是一
1
>>> c=a.reshape(2,-1)
>>> c.ndim # c的维度是2
>>b.reshape(1,-1).ndim #reshape后维度为2
>>> np.concatenate([b.reshape(1,-1),c])
array([[2, 3, 4, 5, 6],
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> b.reshape(1,-1)
array([[2, 3, 4, 5, 6]])
>>> b
array([2, 3, 4, 5, 6])
在垂直方向合并数组:
np.vstack([a,b]) # vstack不需要把一维数组变成二维数组,可以智能合并
>>> np.vstack([b,c])
array([[2, 3, 4, 5, 6],
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> b
array([2, 3, 4, 5, 6])
>>> c
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
再水平方向合并矩阵:
np.hstack([a,b])
>>> np.hstack([a,b])
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, 6])
这三类合并也会自动识别能否合并。
>>> np.hstack([b,c]) # b,c只能水平合并
Traceback (most recent call last):
File "<pyshell#207>", line 1, in <module>
np.hstack([b,c])
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\numpy\core\shape_base.py", line 286, in hstack
return _nx.concatenate(arrs, 0)
ValueError: all the input arrays must have same number of dimensions
Traceback (most recent call last):
File "<pyshell#207>", line 1, in <module>
np.hstack([b,c])
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\numpy\core\shape_base.py", line 286, in hstack
return _nx.concatenate(arrs, 0)
ValueError: all the input arrays must have same number of dimensions
transpose():(类似转置,但是不同)
>>> a
array([[0, 1],
[2, 3]])
>>> np.vstack([a,d])
array([[0, 1],
[2, 3],
[1, 2]])
>>> np.hstack([a,d])
Traceback (most recent call last):
File "<pyshell#436>", line 1, in <module>
np.hstack([a,d])
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\numpy\core\shape_base.py", line 288, in hstack
return _nx.concatenate(arrs, 1)
ValueError: all the input arrays must have same number of dimensions
>>> d
array([1, 2])
>>> d=np.array([[1],
[2]])
>>> d
array([[1],
[2]])
>>> np.hstack([a,d])
array([[0, 1, 1],
[2, 3, 2]])
array([[0, 1],
[2, 3]])
>>> np.vstack([a,d])
array([[0, 1],
[2, 3],
[1, 2]])
>>> np.hstack([a,d])
Traceback (most recent call last):
File "<pyshell#436>", line 1, in <module>
np.hstack([a,d])
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\numpy\core\shape_base.py", line 288, in hstack
return _nx.concatenate(arrs, 1)
ValueError: all the input arrays must have same number of dimensions
>>> d
array([1, 2])
>>> d=np.array([[1],
[2]])
>>> d
array([[1],
[2]])
>>> np.hstack([a,d])
array([[0, 1, 1],
[2, 3, 2]])
矩阵分割:
np.split(ary,indices_or_sections,axis=0)
按行分割axis=0:
>>> b=np.array([i for i in range(16)]).reshape(4,4)
>>> b
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> x,y=np.split(b,[2]) # arg就是b,indices是[2],axis=0
>>> x
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
>>> y
array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])
按列分割(axis=1):
>>> x,y=np.split(b,[2],axis=1)
>>> x
array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]])
>>> y
array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])
其他分割方法:
垂直分割,同axis=0:
np.vsplit(ary,indices_or_sections)
>>> x,y=np.vsplit(ary=b,indices_or_sections=[2])
>>> x
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
>>> y
array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])
水平分割,axis=1:
np.hsplit(ary,indices_or_sections)
>>> x,y=np.hsplit(ary=b,indices_or_sections=[2])
>>> x
array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]])
>>> y
array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])
其他分割
倒数第一列分割:
>>> x,y=np.hsplit(b,[-1]) # -1表示分割点在倒数第一列
>>> x
array([[ 0, 1, 2],
[ 4, 5, 6],
[ 8, 9, 10],
[12, 13, 14]])
>>> y
array([[ 3],
[ 7],
[11],
[15]])
np.array()中的运算:
乘法
>>> a=np.array([i for i in range(10)])
>>> a*2
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
>>> b=[i for i in range(10)]
>>> b*2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
对于列表中用乘法,是将列表扩展一倍,而np.array()则是将每个元素扩大一倍。列表想要得到元素加倍,需要:
>>> c=[] # 先构造一个空列表,对每个元素运算
>>> for i in b:
c.append(i*2)
>>> c
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
比较两种方法的运算时间
>>> import time
# for 循环的方法
>>> d=time.clock()
>>> c=[]
>>> for i in b:
c.append(i*2)
>>> c
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> time.clock()-d
# 返回结果的单位是ms
32.28740595737346
>>> t=time.clock()
>>> a*2
# np.array方法
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
>>> time.clock()-t
17.847634838342472
可见运算时间上,用np.array更快
>>> t=time.clock()
>>> np.array([2*i for i in a])
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
>>> time.clock()-t
57.77788254810349
如果用这种方法,显然更慢,np.array()用for循环
universal Functions
通用于加减乘除,对象是矩阵中所有元素。
>>> b=a.reshape(2,-1)
>>> b
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> b=a.reshape((2,-1)) # 这两种都可以
>>> b
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> b=a.reshape(shape=[2,5]) # 但是这种为啥不可以我就不懂了,按理说里面肯定有shape变量
Traceback (most recent call last):
File "<pyshell#389>", line 1, in <module>
b=a.reshape(shape=[2,5])
TypeError: 'shape' is an invalid keyword argument for this function
>>> b-1 # 减法
array([[-1, 0, 1, 2, 3],
[ 4, 5, 6, 7, 8]])
>>> b+1 # 加法
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])
>>> b*2 # 乘法
array([[ 0, 2, 4, 6, 8],
[10, 12, 14, 16, 18]])
>>> b/2 # 除法
array([[0. , 0.5, 1. , 1.5, 2. ],
[2.5, 3. , 3.5, 4. , 4.5]])
>>> b//2 # 结果变成整数
array([[0, 0, 1, 1, 2],
[2, 3, 3, 4, 4]], dtype=int32)
Traceback (most recent call last):
File "<pyshell#389>", line 1, in <module>
b=a.reshape(shape=[2,5])
TypeError: 'shape' is an invalid keyword argument for this function
>>> b-1 # 减法
array([[-1, 0, 1, 2, 3],
[ 4, 5, 6, 7, 8]])
>>> b+1 # 加法
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])
>>> b*2 # 乘法
array([[ 0, 2, 4, 6, 8],
[10, 12, 14, 16, 18]])
>>> b/2 # 除法
array([[0. , 0.5, 1. , 1.5, 2. ],
[2.5, 3. , 3.5, 4. , 4.5]])
>>> b//2 # 结果变成整数
array([[0, 0, 1, 1, 2],
[2, 3, 3, 4, 4]], dtype=int32)
>>> b**2 # 平方
array([[ 0, 1, 4, 9, 16],
[25, 36, 49, 64, 81]], dtype=int32)
>>> b%2 # 取余数
array([[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1]], dtype=int32)
>>> 1/b # 倒数
Warning (from warnings module):
File "__main__", line 1
RuntimeWarning: divide by zero encountered in true_divide
array([[ inf, 1. , 0.5 , 0.33333333, 0.25 ],
[0.2 , 0.16666667, 0.14285714, 0.125 , 0.11111111]])
>>> np.absolute(b) # 绝对值
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> np.sin(b) # sin函数
array([[ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ],
[-0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849]])
>>> np.cos(b) # cos函数
array([[ 1. , 0.54030231, -0.41614684, -0.9899925 , -0.65364362],
[ 0.28366219, 0.96017029, 0.75390225, -0.14550003, -0.91113026]])
>>> np.tan(b) # tan函数
array([[ 0. , 1.55740772, -2.18503986, -0.14254654, 1.15782128],
[-3.38051501, -0.29100619, 0.87144798, -6.79971146, -0.45231566]])
同样有取对数之类的
矩阵运算:
乘法:
>>> b
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> b.transpose()
array([[0, 5],
[1, 6],
[2, 7],
[3, 8],
[4, 9]])
>>> dot(b,b.transpose()) # 矩阵乘法,需要匹配好行和列
array([[ 30, 80],
[ 80, 255]])
>>> a=np.array([i for i in range(4)]).reshape(2,2)
>>> b=np.full(shape=(2,2),fill_value=2,dtype=None,order='C')
>>> a+b # 矩阵相加
array([[2, 3],
[4, 5]])
>>> a-b # 相减
array([[-2, -1],
[ 0, 1]])
>>> a*b # 对应元素相乘,也就是Hadamard积
array([[0, 2],
[4, 6]])
>>> a
array([[0, 1],
[2, 3]])
>>> b
array([[2, 2],
[2, 2]])
>>> dot(a,b) # 矩阵相乘
array([[ 2, 2],
[10, 10]])
矩阵转置:
>>> a.T
array([[0, 2],
[1, 3]])
Hadamard 积:
>>> a*b # 对应元素相乘,也就是Hadamard积
array([[0, 2],
[4, 6]])
矩阵和向量运算(一维数组和二维数组):
>>> d=np.array([1,2]).transpose() # d是1x2的矩阵,transpose()不在dot运算好像没有意义
>>> d
array([1, 2])
>>> a # a是2x2的矩阵
array([[0, 1],
[2, 3]])
>>> d+a # 运算是矩阵每行都加对应元素
array([[1, 3],
[3, 5]])
transpose()不在dot运算好像没有意义
>>> d
array([1, 2])
>>> a # a是2x2的矩阵
array([[0, 1],
[2, 3]])
>>> d+a # 运算是矩阵每行都加对应元素
array([[1, 3],
[3, 5]])
这在数学上没有意义,因为这是不存在的
其他用法:
np.random.permutation 和 np.random.shuffle区别:
显然这两个函数都是random模块中的函数,但是用于random中,只能处理数,而不能处理矩阵和向量。
首先,这两个函数都是用来打乱矩阵中元素的位置,区别在于,permutation在打乱循序后返回值是一个打乱后的新矩阵,而原矩阵不变。而shuffle函数没有返回值,而且,他是直接打乱原矩阵。
b=np.random.permuation(a) # b 是一个打乱后的函数,打乱的对象是各个行
b=np.random.shuffle(a) # 无返回值,b为空
np.tile(a,reps):
用于对数组复制,组成新数组,reps表示重复的次数。
reps可以是整数,也可以是元组,如reps=(2,3),表示对a的行扩展2倍,列扩展3倍。
>>> a=np.array([[1,2],
[2,3]])
>>> np.tile(a,reps=2) # 整数
array([[1, 2, 1, 2],
[2, 3, 2, 3]])
>>> np.tile(a,reps=np.array([2])) # 单个元素的数组
array([[1, 2, 1, 2],
[2, 3, 2, 3]])
>>> np.tile(a,reps=(2,3)) # 元组
array([[1, 2, 1, 2, 1, 2],
[2, 3, 2, 3, 2, 3],
[1, 2, 1, 2, 1, 2],
[2, 3, 2, 3, 2, 3]])
>>> np.tile(a,reps=(0,3))
array([], shape=(0, 6), dtype=int32)
reps也可以是数组,但是必须是一个元素的数组
np.mean(a,axis,dtype=None):
返回a的平均值。a可以取a中的某些行或列
axis=0表示按行求平均值,axis=1表示按列求平均值。
np.std(a,axis=None,dtype=None):
返回a的标准差,如果axis没有指定,则返回整个数组所有元素的标准差,否则axis=0返回各个列的标准差,axis=1,返回各行的标准差
np.var((a,axis=None,dtype=None,out=None):
同上,只是返回值变成方差
np.linalg linear algorithm线性代数算法
np.linalg.inv(a)
返回a的逆矩阵
np.linalg.norm(x, ord=None, keepdims=False)求范数
ord=None,默认返回二范数
ord=1,返回一范数
ord=2,返回二范数
ord =np.inf,返回无穷范数
numpy.delete(arr,obj,axis=None)
arr:输入向量
obj:表明哪一个子向量应该被移除。可以为整数或一个int型的向量
axis:表明删除哪个轴的子向量,若默认,则返回一个被拉平的向量(insert,append同)
axis =0,表示对行操作
axis =1,表示对列操作
>>> b
array([[1, 5, 2],
[3, 6, 4]])
>>> np.delete(b,1) # 不懂axis=0的操作
array([1, 2, 3, 6, 4])
>>> np.delete(arr=b,obj=2)
array([1, 5, 3, 6, 4])
>>> np.delete(arr=b,obj=0)
array([5, 2, 3, 6, 4])
>>> np.delete(arr=b,obj=1,axis=0) # 删除第二行
array([[1, 5, 2]])
>>> np.delete(arr=b,obj=1,axis=1) # 删除第二列
array([[1, 2],
[3, 4]])
numpy.insert(arr,obj,values,axis=None)
同理,value为插入的数值
arr:为目标向量
obj:为目标位置
value:为想要插入的数值
axis:为插入的维度
>>> a
array([[1, 2],
[3, 4]])
>>> b=np.insert(a,1,[5,6]) # 拉平后再第一个位置后插入
>>> b
array([1, 5, 6, 2, 3, 4])
>>> b=np.insert(a,1,[5,6],axis=0) # 加一行,位置再第二行
>>> b
array([[1, 2],
[5, 6],
[3, 4]])
>>> b=np.insert(a,1,[5,6],axis=1) # 再第二列插入一列
>>> b
array([[1, 5, 2],
[3, 6, 4]])
需要注意value的格式要匹配,如:
>>> c=np.insert(b,1,[7,8],axis=1)
>>> c
array([[1, 7, 5, 2],
[3, 8, 6, 4]])
>>> c=np.insert(b,1,[7,8],axis=0)
Traceback (most recent call last):
File "<pyshell#94>", line 1, in <module>
c=np.insert(b,1,[7,8],axis=0)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\numpy\lib\function_base.py", line 5073, in insert
new[slobj] = values
ValueError: could not broadcast input array from shape (1,2) into shape (1,3)
numpy.append(arr,values,axis=None)
将values插入到目标arr的最后。
注意,这里values跟arr应该为相同维度的向量
>>> np.append(b,1,axis=None)
array([1, 5, 2, 3, 6, 4, 1])
>>> np.append(b,[[7,8,9]],axis=0)
array([[1, 5, 2],
[3, 6, 4],
[7, 8, 9]])
>>> np.append(b,[7,8,9],axis=0)
#错误,维度需要同
>>> np.append(b,[[7,8,9]],axis=0)
array([[1, 5, 2],
[3, 6, 4],
[7, 8, 9]])
np.c_[a, b] and np.r_[a, b]
np.c_[a,b]表示将矩阵a,b按行合并,np.r_[a,b]表示将矩阵按列合并。
>>> a=np.random.randint(0,3,size=(2,4))
>>> b=np.random.randint(0,3,size=(2,4))
>>> a
array([[1, 0, 0, 1],
[1, 0, 2, 2]])
>>> b
array([[1, 0, 1, 2],
[0, 0, 2, 1]])
>>> np.c_[a,b]
array([[1, 0, 0, 1, 1, 0, 1, 2],
[1, 0, 2, 2, 0, 0, 2, 1]])
>>> np.r_[a,b]
array([[1, 0, 0, 1],
[1, 0, 2, 2],
[1, 0, 1, 2],
[0, 0, 2, 1]])
np.sign(x)
对矩阵x做符号运算,大于0的元素判1,小于0判0.返回判决结果。
>>> c=np.random.randint(-2,3,size=(3,4))
>>> c
array([[ 0, -1, 0, -1],
[-1, 1, 2, -2],
[-1, 2, -1, 2]])
>>> np.sign(c)
array([[ 0, -1, 0, -1],
[-1, 1, 1, -1],
[-1, 1, -1, 1]])