使用Numpy模块进行矩阵运算,直接使用a+b为相应位置的元素相加,与普通的运算一样,也可以使用关系运算符,得到布尔矩阵
若要进行矩阵乘法使用:
c_dot = np.dot(a,b)
if a * b , output is the product of corresponding elements of array
此外可以a@b, a.dot(b)来计算矩阵式
使用随机数来组成一个矩阵:
a=np.random.random((2,4)) #2行4列
如上默认生成0到1之间的随机数
可以对矩阵的元素进行一系列的操作:
np.sum(a)
np.min(a)
np.max(a)
如果你需要对行或者列进行查找运算,就需要在上述代码中为 axis 进行赋值。 当axis的值为0的时候,将会以列作为查找单元, 当axis的值为1的时候,将会以行作为查找单元。
>>> a = np.random.random((2,4))
>>> a
array([[0.64428267, 0.25034672, 0.89722116, 0.13677665],
[0.22217028, 0.13405467, 0.6815061 , 0.51201267]])
>>> a.sum(axis=0)
array([0.86645295, 0.38440138, 1.57872726, 0.64878933])
>>> a.sum(axis=1)
array([1.9286272 , 1.54974372])
>>>
还可以进行各种计算,eg:
>>> B
array([0, 1, 2])
>>> np.exp(B)
array([ 1. , 2.71828183, 7.3890561 ])
>>> np.sqrt(B)
array([ 0. , 1. , 1.41421356])
numpy.
sort
(a, axis=-1, kind='quicksort', order=None)[source]
Return a sorted copy of an array.
Parameters: | a : array_like Array to be sorted. axis : int or None, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional Sorting algorithm. Default is ‘quicksort’. order : str or list of str, optional When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. |
---|
numpy.
argsort
(a,axis = -1,kind ='quicksort',order = None )
返回对数组进行排序的索引。
使用kind关键字指定的算法沿给定轴执行间接排序。它返回相同的形状的索引数组 一个沿着以排序的顺序给定的轴线索引数据。
参数: | a : array_like 要排序的数组。 axis : int或None,可选 Axis沿着它排序。默认值为-1(最后一个轴)。如果为None,则使用扁平化阵列。 kind : {'quicksort','mergesort','heapsort','stable'},可选 排序算法。 order : str或str的列表,可选 当a是一个定义了字段的数组时,此参数指定要比较哪些字段的第一个,第二个等。可以将单个字段指定为字符串,并且不需要指定所有字段,但仍将使用未指定的字段,他们在dtype中出现的顺序,以打破关系。 |
---|---|
返回: | index_array : ndarray,int 索引的阵列那种一个沿指定轴线。如果a是一维的,则 |