Numpy的基本运算操作

一、四则运算(运算都作用在各个元素上,可理解为批量操作):

  1. 加 a+b
  2. 减 a-b
  3. 乘 a*b   (注意:不是矩阵或向量乘法)
  4. 除 a/b
>>> a = np.ones((2,3))
>>> b = np.random.rand(2,3)
>>> a + b
array([[ 1.31103566,  1.80777764,  1.66783499],
       [ 1.12616354,  1.76684873,  1.18431413]])
>>> a - b
array([[ 0.68896434,  0.19222236,  0.33216501],
       [ 0.87383646,  0.23315127,  0.81568587]])
>>> a * b
array([[ 0.31103566,  0.80777764,  0.66783499],
       [ 0.12616354,  0.76684873,  0.18431413]])
>>> a / b
array([[ 3.21506541,  1.23796445,  1.49737586],
       [ 7.92621993,  1.30403815,  5.42552009]])

二、矩阵运算:

np.dot表示向量点积或者矩阵运算,两个向量可以直接做点积,不需要转置。

Unlike in many matrix languages, the product operator * operates elementwise in NumPy arrays. The matrix product can be performed using the dot function or method

>>> A = np.array( [[1,1],
...             [0,1]] )
>>> B = np.array( [[2,0],
...             [3,4]] )
>>> A*B                         # elementwise product
array([[2, 0],
       [0, 4]])
>>> A.dot(B)                    # matrix product
array([[5, 4],
       [3, 4]])
>>> np.dot(A, B)                # another matrix product
array([[5, 4],
       [3, 4]])

三、通用函数

包括如求和,开方,求均值等函数,非常方便。

NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called “universal functions”(ufunc). Within NumPy, these functions operate elementwise on an array, producing an array as output.

>>> B = np.arange(3)
>>> B
array([0, 1, 2])
>>> np.exp(B)
array([ 1.        ,  2.71828183,  7.3890561 ])
>>> np.sqrt(B)
array([ 0.        ,  1.        ,  1.41421356])
>>> C = np.array([2., -1., 4.])
>>> np.add(B, C)
array([ 2.,  0.,  6.])

 

转载于:https://my.oschina.net/amhuman/blog/894190

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值