常用numpy模块用法总结
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.ndim2
>>> carray([[1, 2],[2, 3]])
>>> d=np.array([[1], # 2X1矩阵[2]])>>> darray([[1],[2]])
[2]])>>> darray([[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')
>>> aarray([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)])>>> aarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b=a.reshape(2,-1)>>> barray([[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.size10
>>> b.size10
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]])
同样的:
>>> carray([[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].ndim1
子数组:
>>> subc=c[:2,1:] # 取前两行,后四列>>> subcarray([[3, 7, 7, 1],[8, 2, 7, 0]])
>>> subc[1,2] # 索引元素7
>>> subc[1,2]=4 # 修改元素>>> subcarray([[3, 7, 7, 1],[8, 2, 4, 0]])
>>> carray([[3, 3, 7, 7, 1],[0, 8, 2, 4, 0],[1, 0, 8, 5, 3]])
可以发现子数组中的元素改变,整个数组元素都会改变。
但是有时候不想这样。
可以用array.copy()函数:
>>> subc=c.copy()>>> subcarray([[3, 3, 7, 7, 1],[0, 8, 2, 4, 0],[1, 0, 8, 5, 3]])
>>> subc[2,3]5
>>> subc[2,3]=2>>> subcarray([[3, 3, 7, 7, 1],[0, 8, 2, 4, 0],[1, 0, 8, 2, 3]])
>>> carray([[3, 3, 7, 7, 1],[0, 8, 2, 4, 0],[1, 0, 8, 5, 3]])
2, 3]])
>>> carray([[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])
>>> aarray([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)])>>> barray([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]])
>>> barray([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]])
>>> barray([2, 3, 4, 5, 6])
>>> carray([[0, 1, 2, 3, 4],[5, 6, 7, 8, 9]])
>>> aarray([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 hstackreturn _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 hstackreturn _nx.concatenate(arrs, 0)
ValueError: all the input arrays must have same number of dimensions
transpose():(类似转置,但是不同)
>>> aarray([[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 hstackreturn _nx.concatenate(arrs, 1)
ValueError: all the input arrays must have same number of dimensions
>>> darray([1, 2])
>>> d=np.array([[1],[2]])>>> darray([[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 hstackreturn _nx.concatenate(arrs, 1)
ValueError: all the input arrays must have same number of dimensions
>>> darray([1, 2])
>>> d=np.array([[1],[2]])>>> darray([[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)>>> barray([[ 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>>> xarray([[0, 1, 2, 3],[4, 5, 6, 7]])
>>> yarray([[ 8, 9, 10, 11],[12, 13, 14, 15]])
按列分割(axis=1):
>>> x,y=np.split(b,[2],axis=1)>>> xarray([[ 0, 1],[ 4, 5],[ 8, 9],[12, 13]])
>>> yarray([[ 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]) >>> xarray([[0, 1, 2, 3],[4, 5, 6, 7]])
>>> yarray([[ 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])>>> xarray([[ 0, 1],[ 4, 5],[ 8, 9],[12, 13]])
>>> yarray([[ 2, 3],[ 6, 7],[10, 11],[14, 15]])
其他分割
倒数第一列分割:
>>> x,y=np.hsplit(b,[-1]) # -1表示分割点在倒数第一列>>> xarray([[ 0, 1, 2],[ 4, 5, 6],[ 8, 9, 10],[12, 13, 14]])
>>> yarray([[ 3],[ 7],[11],[15]])
np.array()中的运算:
乘法
>>> a=np.array([i for i in range(10)])>>> a*2array([ 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()-t17.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()-t57.77788254810349
如果用这种方法,显然更慢,np.array()用for循环
universal Functions
通用于加减乘除,对象是矩阵中所有元素。
>>> b=a.reshape(2,-1)>>> barray([[0, 1, 2, 3, 4],[5, 6, 7, 8, 9]])
>>> b=a.reshape((2,-1)) # 这两种都可以>>> barray([[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]])
同样有取对数之类的
矩阵运算:
乘法:
>>> barray([[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]])
>>> aarray([[0, 1],[2, 3]])
>>> barray([[2, 2],[2, 2]])
>>> dot(a,b) # 矩阵相乘array([[ 2, 2],[10, 10]])
矩阵转置:
>>> a.Tarray([[0, 2],[1, 3]])
Hadamard 积:
>>> a*b # 对应元素相乘,也就是Hadamard积array([[0, 2],[4, 6]])
矩阵和向量运算(一维数组和二维数组):
>>> d=np.array([1,2]).transpose() # d是1x2的矩阵,transpose()不在dot运算好像没有意义
>>> darray([1, 2])
>>> a # a是2x2的矩阵array([[0, 1],[2, 3]])>>> d+a # 运算是矩阵每行都加对应元素array([[1, 3],[3, 5]])
transpose()不在dot运算好像没有意义
>>> darray([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 insertnew[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]])
常用numpy模块用法总结相关推荐
- python常用模块用法_python笔记之常用模块用法分析
python笔记之常用模块用法分析 内置模块(不用import就可以直接使用) 常用内置函数 help(obj) 在线帮助, obj可是任何类型 callable(obj) 查看一个obj是不是可以像 ...
- python常用模块用法_python常用模块(一)
#什么是模块呢?就是用一大坨代码来完成一个功能的代码集合,是不是简单易懂 #类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个 ...
- python复数计算符号_Python:基本运算、基本函数(包括复数)、Math模块、NumPy模块...
基本运算 x**2 : x^2 若x是mat矩阵,那就表示x内每个元素求平方 inf:表示正无穷 逻辑运算符:and,or,not 基本函数 字典的get方法 a.get(k,d)11 get相当于一 ...
- Python~NumPy模块一站式教程,稳稳拿捏(持续更新ing)
一.Numpy模块 基础 1. 介绍 NumPy的核心是多维数组类numpy.ndarray,矩阵类numpy.matrix是多位数组类的派生类.以多位数组类为数据组织结构,Numpy提供了众多的数学 ...
- python中的numpy模块
参考 python中的numpy模块 - 云+社区 - 腾讯云 目录 NumPy 教程 学习本教程前你需要了解 NumPy 应用 相关链接 NumPy 安装 1.使用已有的发行版本 2.使用 pip ...
- python 数据分析模块_Python数据分析pandas模块用法实例详解
本文实例讲述了Python数据分析pandas模块用法.分享给大家供大家参考,具体如下: pandas pandas10分钟入门,可以查看官网:10 minutes to pandas 也可以查看更复 ...
- python pillow库_python pillow模块用法
pillow Pillow是PIL的一个派生分支,但如今已经发展成为比PIL本身更具活力的图像处理库.pillow可以说已经取代了PIL,将其封装成python的库(pip即可安装),且支持pytho ...
- python常用模块大全总结-常用python模块
广告关闭 2017年12月,云+社区对外发布,从最开始的技术博客到现在拥有多个社区产品.未来,我们一起乘风破浪,创造无限可能. python常用模块什么是模块? 常见的场景:一个模块就是一个包含了py ...
- python安装numpy模块-python的numpy模块安装不成功简单解决方法总结
为了画个图,被numpy这个模块的安装真的折腾疯了!!!一直装不上,花了几个小时,看了网上的很多教程.方法发现总结得不是很全,这里总结一下,防止大家再出现这个问题没有解决方法. Python的魅力之一 ...
最新文章
- c语言如何输出斜杠星号,Excel 如何提取出最后一个斜杠开始的数字
- cmake中添加 -g编译选项
- WildFly Kubernetes exec探针
- 阿里云Quick BI——让人人都成为分析师
- Emlog百度快速收录插件
- sqlmap源码阅读_setPreprocessFunctions和_setPostprocessFunctions
- 关于学计算机有什么用检讨书,旷计算机课检讨书
- 2018国庆雅礼D3T1
- mysql可视化界面数据导出_MySQL 使用可视化工具导出与导入数据
- 常见机器人离线编程软件对比
- 什么是WBS分解法?
- Js 将数字转换为大写金额
- Centos8安装谷歌浏览器
- LaTex-使用texstudio插入参考文献
- mybatis PageHelper.startPage出现limit错误
- html之圆形用户头像
- 空间信息产业的八大极客技术
- 微信小程序-canvas 2d带动画的半圆形刻度进度条
- 数据库修改表名,字段名 字段类型
- 【LaTeX】LaTeX新手入门教程-基础排版
热门文章
- F8-Nginx代理缓存负载均衡后端均衡
- 维基解密:科技公司获得安全漏洞信息须答应几个条件
- Oracle如何根据SQL_TEXT生成SQL_ID
- mysql停止更新时间_我如何更新这个MySQL查询以获取从开始、停止、暂停和恢复事件经过的总时间...
- 商户权限表mysql_MySQL 事务之 Yii2.0 商户提现
- 每日一“酷”之string
- android httppost
- 简单内网***刺探命令
- mysql基础知识(二)
- 摘抄和总结--确保搞砸人工智能项目的十种方法