Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
NumPy
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Examples == <syntaxhighlight lang="numpy"> import numpy as np from numpy.random import rand from numpy.linalg import solve, inv a = np.array([[1, 2, 3, 4], [3, 4, 6, 7], [5, 9, 0, 5]]) a.transpose() </syntaxhighlight> === Basic operations === <syntaxhighlight lang="numpy"> >>> a = np.array([1, 2, 3, 6]) >>> b = np.linspace(0, 2, 4) # create an array with four equally spaced points starting with 0 and ending with 2. >>> c = a - b >>> c array([ 1. , 1.33333333, 1.66666667, 4. ]) >>> a**2 array([ 1, 4, 9, 36]) </syntaxhighlight> === Universal functions === <syntaxhighlight lang="numpy"> >>> a = np.linspace(-np.pi, np.pi, 100) >>> b = np.sin(a) >>> c = np.cos(a) >>> >>> # Functions can take both numbers and arrays as parameters. >>> np.sin(1) 0.8414709848078965 >>> np.sin(np.array([1, 2, 3])) array([0.84147098, 0.90929743, 0.14112001]) </syntaxhighlight> === Linear algebra === <syntaxhighlight lang="numpy"> >>> from numpy.random import rand >>> from numpy.linalg import solve, inv >>> a = np.array([[1, 2, 3], [3, 4, 6.7], [5, 9.0, 5]]) >>> a.transpose() array([[ 1. , 3. , 5. ], [ 2. , 4. , 9. ], [ 3. , 6.7, 5. ]]) >>> inv(a) array([[-2.27683616, 0.96045198, 0.07909605], [ 1.04519774, -0.56497175, 0.1299435 ], [ 0.39548023, 0.05649718, -0.11299435]]) >>> b = np.array([3, 2, 1]) >>> solve(a, b) # solve the equation ax = b array([-4.83050847, 2.13559322, 1.18644068]) >>> c = rand(3, 3) * 20 # create a 3x3 random matrix of values within [0,1] scaled by 20 >>> c array([[ 3.98732789, 2.47702609, 4.71167924], [ 9.24410671, 5.5240412 , 10.6468792 ], [ 10.38136661, 8.44968437, 15.17639591]]) >>> np.dot(a, c) # matrix multiplication array([[ 53.61964114, 38.8741616 , 71.53462537], [ 118.4935668 , 86.14012835, 158.40440712], [ 155.04043289, 104.3499231 , 195.26228855]]) >>> a @ c # Starting with Python 3.5 and NumPy 1.10 array([[ 53.61964114, 38.8741616 , 71.53462537], [ 118.4935668 , 86.14012835, 158.40440712], [ 155.04043289, 104.3499231 , 195.26228855]]) </syntaxhighlight> === Multidimensional arrays === <syntaxhighlight lang="numpy"> >>> M = np.zeros(shape=(2, 3, 5, 7, 11)) >>> T = np.transpose(M, (4, 2, 1, 3, 0)) >>> T.shape (11, 5, 3, 7, 2) </syntaxhighlight> === Incorporation with OpenCV === <syntaxhighlight lang="numpy"> >>> import numpy as np >>> import cv2 >>> r = np.reshape(np.arange(256*256)%256,(256,256)) # 256x256 pixel array with a horizontal gradient from 0 to 255 for the red color channel >>> g = np.zeros_like(r) # array of same size and type as r but filled with 0s for the green color channel >>> b = r.T # transposed r will give a vertical gradient for the blue color channel >>> cv2.imwrite("gradients.png", np.dstack([b,g,r])) # OpenCV images are interpreted as BGR, the depth-stacked array will be written to an 8bit RGB PNG-file called "gradients.png" True </syntaxhighlight> === Nearest-neighbor search === Iterative Python algorithm and vectorized NumPy version. <syntaxhighlight lang="numpy"> >>> # # # Pure iterative Python # # # >>> points = [[9,2,8],[4,7,2],[3,4,4],[5,6,9],[5,0,7],[8,2,7],[0,3,2],[7,3,0],[6,1,1],[2,9,6]] >>> qPoint = [4,5,3] >>> minIdx = -1 >>> minDist = -1 >>> for idx, point in enumerate(points): # iterate over all points ... dist = sum([(dp-dq)**2 for dp,dq in zip(point,qPoint)])**0.5 # compute the euclidean distance for each point to q ... if dist < minDist or minDist < 0: # if necessary, update minimum distance and index of the corresponding point ... minDist = dist ... minIdx = idx >>> print(f"Nearest point to q: {points[minIdx]}") Nearest point to q: [3, 4, 4] >>> # # # Equivalent NumPy vectorization # # # >>> import numpy as np >>> points = np.array([[9,2,8],[4,7,2],[3,4,4],[5,6,9],[5,0,7],[8,2,7],[0,3,2],[7,3,0],[6,1,1],[2,9,6]]) >>> qPoint = np.array([4,5,3]) >>> minIdx = np.argmin(np.linalg.norm(points-qPoint, axis=1)) # compute all euclidean distances at once and return the index of the smallest one >>> print(f"Nearest point to q: {points[minIdx]}") Nearest point to q: [3 4 4] </syntaxhighlight> === F2PY === Quickly wrap native code for faster scripts.<ref>{{cite web |title=F2PY docs from NumPy |url=https://numpy.org/doc/stable/f2py/usage.html?highlight=f2py |publisher=NumPy |access-date=18 April 2022}}</ref><ref>{{cite web |last1=Worthey |first1=Guy |title=A python vs. Fortran smackdown |url=https://guyworthey.net/2022/01/03/a-python-vs-fortran-smackdown/ |website=Guy Worthey |date=3 January 2022 |publisher=Guy Worthey |access-date=18 April 2022}}</ref><ref>{{cite web |last1=Shell |first1=Scott |title=Writing fast Fortran routines for Python |url=https://sites.engineering.ucsb.edu/~shell/che210d/f2py.pdf |website=UCSB Engineering Department |publisher=University of California, Santa Barbara |access-date=18 April 2022}}</ref> <syntaxhighlight lang="fortran"> ! Python Fortran native code call example ! f2py -c -m foo *.f90 ! Compile Fortran into python named module using intent statements ! Fortran subroutines only not functions--easier than JNI with C wrapper ! requires gfortran and make subroutine ftest(a, b, n, c, d) implicit none integer, intent(in) :: a, b, n integer, intent(out) :: c, d integer :: i c = 0 do i = 1, n c = a + b + c end do d = (c * n) * (-1) end subroutine ftest </syntaxhighlight> <syntaxhighlight lang="pycon"> >>> import numpy as np >>> import foo >>> a = foo.ftest(1, 2, 3) # or c,d = instead of a.c and a.d >>> print(a) (9,-27) >>> help("foo.ftest") # foo.ftest.__doc__ </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)