大小相等的数组之间的任何算术运算,会应用到元素级别

>>> a = np.array( [20,30,40,50] )
>>> b = np.arange( 4 )
>>> b
array([0, 1, 2, 3])
>>> c = a-b
>>> c
array([20, 29, 38, 47])

数组与标量的算术运算也会将这个标量值传播到各个元素

>>> b**2
array([0, 1, 4, 9])

三角运算

>>> 10*np.sin(a)
array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])

关系运算

>>> a<35
array([ True, True, False, False], dtype=bool)

元素乘积

>>> 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]])

+=或*=运算

>>> a = np.ones((2,3), dtype=int)
>>> b = np.random.random((2,3))
>>> a *= 3
>>> a
array([[3, 3, 3],
       [3, 3, 3]])
>>> b += a
>>> b
array([[ 3.417022  ,  3.72032449,  3.00011437],
       [ 3.30233257,  3.14675589,  3.09233859]])

当使用不同类型的数组操作时,结果类型对应于更为精确的数组

>>> a = np.ones(3, dtype=np.int32)
>>> b = np.linspace(0,pi,3)
>>> b.dtype.name
'float64'
>>> c = a+b
>>> c
array([ 1.        ,  2.57079633,  4.14159265])
>>> c.dtype.name
'float64'

统计操作

创建随机数组

>>> a = np.random.random((2,3))
>>> a
array([[ 0.18626021,  0.34556073,  0.39676747],
       [ 0.53881673,  0.41919451,  0.6852195 ]])

统计和

>>> a.sum()
2.5718191614547998

最小值

>>> a.min()
0.1862602113776709

最大值

>>> a.max()
0.6852195003967595

通过指定axis参数,可以设定指定轴上的操作。创建3x4数组

>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

统计每一列的和

>>> b.sum(axis=0)                            # sum of each column
array([12, 15, 18, 21])

每一行的最小值

>>> b.min(axis=1)                            # min of each row
array([0, 4, 8])

每一行的累计和

>>> b.cumsum(axis=1)                         # cumulative sum along each row
array([[ 0,  1,  3,  6],
       [ 4,  9, 15, 22],
       [ 8, 17, 27, 38]])

数学函数

Numpy提供熟悉的数学函数,这些函数将在元素级别上作用

构建1维数组

>>> B = np.arange(3)
>>> B
array([0, 1, 2])

对数组元素取e

>>> np.exp(B)
array([ 1.        ,  2.71828183,  7.3890561 ])

对数组元素sqrt

>>> np.sqrt(B)
array([ 0.        ,  1.        ,  1.41421356])

对数组元素执行add

>>> C = np.array([2., -1., 4.])
>>> np.add(B, C)
array([ 2.,  0.,  6.])

results matching ""

    No results matching ""