ndarray对象的基本操作

ndarray对象的基本操作

• 加减乘除四则运算

``````  >>> a = np.full((3,3),3)
>>> a
array([[3, 3, 3],
[3, 3, 3],
[3, 3, 3]])
>>> a+1
array([[4, 4, 4],
[4, 4, 4],
[4, 4, 4]])
>>> a-2
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
>>> a*5
array([[15, 15, 15],
[15, 15, 15],
[15, 15, 15]])
>>> a/3
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
>>> a
array([[3, 3, 3],
[3, 3, 3],
[3, 3, 3]])

>>> b = np.full((3,3),3)
>>> b
array([[3, 3, 3],
[3, 3, 3],
[3, 3, 3]])
>>> a+b
array([[6, 6, 6],
[6, 6, 6],
[6, 6, 6]])
>>> a += b
>>> a
array([[6, 6, 6],
[6, 6, 6],
[6, 6, 6]])
``````

注意：虽然可以对两个ndarray对象进行操作，但是如果没有赋值，不会改变原来的ndarray对象

当对两个ndarray对象数据类型精度不一样进行操作时，结果的精度为更精确的那个数据类型
``````>>> a = np.array([[0.1,0.2,0.3],[0.3,0.2,0.1]],dtype=np.float32)
>>> a
array([[0.1, 0.2, 0.3],
[0.3, 0.2, 0.1]], dtype=float32)
>>> b = np.array([[0.3,0.2,0.1],[0.1,0.2,0.3]],dtype=np.float64)
>>> b
array([[0.3, 0.2, 0.1],
[0.1, 0.2, 0.3]])
>>> c = a+b
>>> c
array([[0.4       , 0.4       , 0.40000001],
[0.40000001, 0.4       , 0.4       ]])
>>> c.dtype
dtype('float64')
``````
• 常用数学函数sum、min、max等
``````>>> a = np.arange(12).reshape(4,3) # reshape可以设置输出时的维度
>>> a
array([[ 0,  1,  2],
[ 3,  4,  5],
[ 6,  7,  8],
[ 9, 10, 11]])
>>> a.sum()
66
>>> a.sum(axis=0)   # axis=0表示求列的相关操作
array([18, 22, 26]) # axis=1表示求行的相关操作
>>> a.sum(axis=1)
array([ 3, 12, 21, 30])
>>> a.min()
0
>>> a.min(axis=0)
array([0, 1, 2])
>>> a.min(axis=1)
array([0, 3, 6, 9])
>>> a.max()
11
>>> a.max(axis=0)
array([ 9, 10, 11])
>>> a.max(axis=1)
array([ 2,  5,  8, 11])
>>> np.sin(a)
array([[ 0.        ,  0.84147098,  0.90929743],
[ 0.14112001, -0.7568025 , -0.95892427],
[-0.2794155 ,  0.6569866 ,  0.98935825],
[ 0.41211849, -0.54402111, -0.99999021]])
>>> np.cos(a)
array([[ 1.        ,  0.54030231, -0.41614684],
[-0.9899925 , -0.65364362,  0.28366219],
[ 0.96017029,  0.75390225, -0.14550003],
[-0.91113026, -0.83907153,  0.0044257 ]])
>>> np.tan(a)
array([[ 0.00000000e+00,  1.55740772e+00, -2.18503986e+00],
[-1.42546543e-01,  1.15782128e+00, -3.38051501e+00],
[-2.91006191e-01,  8.71447983e-01, -6.79971146e+00],
[-4.52315659e-01,  6.48360827e-01, -2.25950846e+02]])``````
• 类似于python中列表的操作
• 索引,一维数组的索引和列表一样，多维数组的索引需要根据维度索引
``````>>> a = np.arange(12)
>>> a
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
>>> a[0]
0
>>> a[11]
11
>>> b = np.arange(12).reshape(2,6)
>>> b[0,0]
0
>>> b[5,5]
>>> b[1,5]
11``````
• 切片，与python中的列表相似，也是左包含右不包含
``````>>> b[:,5]
array([ 5, 11])
>>> b[1,1:2]
array([7])
>>> b[1,1:5]
array([ 7,  8,  9, 10])``````
多维数组切片时，一定要注意好维度，根据维度来切片
• 迭代，与python的列表相似，都可以用for in 来遍历ndarray对象，一维数组遍历和列表一样，多维数组遍历会得到次维的数组
``````>>> for i in b:
...     print(i)
...
[0 1 2 3 4 5]
[ 6  7  8  9 10 11]``````