Array transpose and axis exchange
In [4]: arr = np.random.randn(3,2) In [5]: arr.T Out[5]: array([[-1.61958612, 0.51404498, 1.27702971], [-1.49568441, -0.62306175, 0.27173435]]) In [6]: np.dot(arr.T,arr) Out[6]: array([[4.5181063 , 2.44912079], [2.44912079, 2.69911737]])
In [7]: arr = np.arange(16).reshape((2,2,4)) In [8]: arr Out[8]: array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [12, 13, 14, 15]]]) In [9]: arr.transpose((1,0,2)) Out[9]: array([[[ 0, 1, 2, 3], [ 8, 9, 10, 11]], [[ 4, 5, 6, 7], [12, 13, 14, 15]]])
Post needs to get a tuple with axis numbers to transpose these axes
In [10]: arr.swapaxes(1,2) Out[10]: array([[[ 0, 4], [ 1, 5], [ 2, 6], [ 3, 7]], [[ 8, 12], [ 9, 13], [10, 14], [11, 15]]])
Universal function
In [11]: arr = np.arange(10) In [12]: arr Out[12]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [13]: np.sqrt(arr) Out[13]: array([0. , 1. , 1.41421356, 1.73205081, 2. , 2.23606798, 2.44948974, 2.64575131, 2.82842712, 3. ]) In [14]: np.exp(arr) Out[14]: array([1.00000000e+00, 2.71828183e+00, 7.38905610e+00, 2.00855369e+01, 5.45981500e+01, 1.48413159e+02, 4.03428793e+02, 1.09663316e+03, 2.98095799e+03, 8.10308393e+03])
There are many functions, you can go to the official website to check
Data processing with array
In [16]: point Out[16]: array([1, 2, 3, 4]) In [17]: xs,ys = np.meshgrid(point,point) In [18]: xs Out[18]: array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) In [19]: ys Out[19]: array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]) In [20]: z = np.sqrt(xs**2+ys**2) In [21]: z Out[21]: array([[1.41421356, 2.23606798, 3.16227766, 4.12310563], [2.23606798, 2.82842712, 3.60555128, 4.47213595], [3.16227766, 3.60555128, 4.24264069, 5. ], [4.12310563, 4.47213595, 5. , 5.65685425]])
Conditional logic expression array calculation
In [23]: xarr = np.array([1.1,1.2,1.3,1.4,1.5]) In [24]: yarr = np.array([2.1,2.2,2.3,2.4,2.5]) In [25]: cond = np.array([True,False,True,True,False]) In [26]: result = [(x if c else y) for x,y,c in zip (xarr,yarr,cond)] In [27]: result Out[27]: [1.1, 2.2, 1.3, 1.4, 2.5] In [28]: result = np.where(cond,xarr,yarr) In [29]: result Out[29]: array([1.1, 2.2, 1.3, 1.4, 2.5])
numpy.where can use x if condition esle y, which is not very fast; it cannot be used for multidimensional arrays. np.where is simpler; np.where is conditional on and, or, illogical computation