0% found this document useful (0 votes)
18 views8 pages

NumPy: Plotting Sin(x) with Matplotlib

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views8 pages

NumPy: Plotting Sin(x) with Matplotlib

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NumPy

NumPy (pronounced /ˈnʌmpaɪ/ NUM-py) is a


NumPy
library for the Python programming language,
adding support for large, multi-dimensional
arrays and matrices, along with a large
collection of high-level mathematical functions
to operate on these arrays.[3] The predecessor of
NumPy, Numeric, was originally created by Jim
Hugunin with contributions from several other
developers. In 2005, Travis Oliphant created
NumPy by incorporating features of the
competing Numarray into Numeric, with
extensive modifications. NumPy is open-source
software and has many contributors. NumPy is
fiscally sponsored by NumFOCUS.[4]

Plot of y=sin(x) function, created with NumPy


History and Matplotlib libraries
Original author Travis Oliphant
Developer Community project
matrix-sig
Initial release As Numeric, 1995; as
The Python programming language was not NumPy, 2006
originally designed for numerical computing,
Stable release 2.3.5[1] / 16 November 2025
but attracted the attention of the scientific and
engineering community early on. In 1995 the Repository [Link]/numpy/numpy
special interest group (SIG) matrix-sig was ([Link]
founded with the aim of defining an array numpy)
computing package; among its members was Written in Python, C
Python designer and maintainer Guido van Operating system Cross-platform
Rossum, who extended Python's syntax (in
Type Numerical analysis
particular the indexing syntax[5]) to make array
computing easier.[6] License BSD[2]
Website [Link] ([Link]
rg/)
Numeric
An implementation of a matrix package was completed by Jim Fulton, then generalized by
Jim Hugunin and called Numeric[6] (also variously known as the "Numerical Python
extensions" or "NumPy"), with influences from the APL family of languages, Basis, MATLAB,
FORTRAN, S and S+, and others.[7][8] Hugunin, a graduate student at the Massachusetts
Institute of Technology (MIT),[8]: 10 joined the Corporation for National Research Initiatives
(CNRI) in 1997 to work on JPython,[6] leaving Paul Dubois of Lawrence Livermore National
Laboratory (LLNL) to take over as maintainer.[8]: 10 Other early contributors include David
Ascher, Konrad Hinsen and Travis Oliphant.[8]: 10
Numarray
A new package called Numarray was written as a more flexible replacement for Numeric.[9]
Like Numeric, it too is now deprecated.[10][11] Numarray had faster operations for large
arrays, but was slower than Numeric on small ones,[12] so for a time both packages were
used in parallel for different use cases. The last version of Numeric (v24.2) was released on
11 November 2005, while the last version of numarray (v1.5.2) was released on 24 August
2006.[13]

There was a desire to get Numeric into the Python standard library, but Guido van Rossum
decided that the code was not maintainable in its state then.[14]

NumPy
In early 2005, NumPy developer Travis Oliphant wanted to unify the community around a
single array package and ported Numarray's features to Numeric, releasing the result as
NumPy 1.0 in 2006.[9] This new project was part of SciPy. To avoid installing the large SciPy
package just to get an array object, this new package was separated and called NumPy.
Support for Python 3 was added in 2011 with NumPy version 1.5.0.[15]

In 2011, PyPy started development on an implementation of the NumPy API for PyPy.[16] As
of 2023, it is not yet fully compatible with NumPy.[17]

Features
NumPy targets the CPython reference implementation of Python, which is a non-optimizing
bytecode interpreter. Mathematical algorithms written for this version of Python often run
much slower than compiled equivalents due to the absence of compiler optimization.
NumPy addresses the slowness problem partly by providing multidimensional arrays and
functions and operators that operate efficiently on arrays; using these requires rewriting
some code, mostly inner loops, using NumPy.

Using NumPy in Python gives functionality comparable to MATLAB since they are both
interpreted,[18] and they both allow the user to write fast programs as long as most
operations work on arrays or matrices instead of scalars. In comparison, MATLAB boasts a
large number of additional toolboxes, notably Simulink, whereas NumPy is intrinsically
integrated with Python, a more modern and complete programming language. Moreover,
complementary Python packages are available; SciPy is a library that adds more MATLAB-
like functionality and Matplotlib is a plotting package that provides MATLAB-like plotting
functionality. Although MATLAB can perform sparse matrix operations, NumPy alone
cannot perform such operations and requires the use of the [Link] library. Internally,
both MATLAB and NumPy rely on BLAS and LAPACK for efficient linear algebra
computations.

Python bindings of the widely used computer vision library OpenCV utilize NumPy arrays
to store and operate on data. Since images with multiple channels are simply represented
as three-dimensional arrays, indexing, slicing or masking with other arrays are very
efficient ways to access specific pixels of an image. The NumPy array as universal data
structure in OpenCV for images, extracted feature points, filter kernels and many more
vastly simplifies the programming workflow and debugging.

Importantly, many NumPy operations release the global interpreter lock, which allows for
multithreaded processing.[19]

NumPy also provides a C API, which allows Python code to interoperate with external
libraries written in low-level languages.[20]

The ndarray data structure


The core functionality of NumPy is its "ndarray", for n-dimensional array, data structure.
These arrays are strided views on memory.[9] In contrast to Python's built-in list data
structure, these arrays are homogeneously typed: all elements of a single array must be of
the same type.

Such arrays can also be views into memory buffers allocated by C/C++, Python, and Fortran
extensions to the CPython interpreter without the need to copy data around, giving a
degree of compatibility with existing numerical libraries. This functionality is exploited by
the SciPy package, which wraps a number of such libraries (notably BLAS and LAPACK).
NumPy has built-in support for memory-mapped ndarrays.[9]

Limitations
Inserting or appending entries to an array is not as trivially possible as it is with Python's
lists. The [Link](...) routine to extend arrays actually creates new arrays of the desired
shape and padding values, copies the given array into the new one and returns it. NumPy's
[Link]([a1,a2]) operation does not actually link the two arrays but returns a
new one, filled with the entries from both given arrays in sequence. Reshaping the
dimensionality of an array with [Link](...) is only possible as long as the number
of elements in the array does not change. These circumstances originate from the fact that
NumPy's arrays must be views on contiguous memory buffers.

Algorithms that are not expressible as a vectorized operation will typically run slowly
because they must be implemented in "pure Python", while vectorization may increase
memory complexity of some operations from constant to linear, because temporary arrays
must be created that are as large as the inputs. Runtime compilation of numerical code has
been implemented by several groups to avoid these problems; open source solutions that
interoperate with NumPy include numexpr[21] and Numba.[22] Cython and Pythran are
static-compiling alternatives to these.

Many modern large-scale scientific computing applications have requirements that exceed
the capabilities of the NumPy arrays. For example, NumPy arrays are usually loaded into a
computer's memory, which might have insufficient capacity for the analysis of large
datasets. Further, NumPy operations are executed on a single CPU. However, many linear
algebra operations can be accelerated by executing them on clusters of CPUs or of
specialized hardware, such as GPUs and TPUs, which many deep learning applications rely
on. As a result, several alternative array implementations have arisen in the scientific
python ecosystem over the recent years, such as Dask for distributed arrays and
TensorFlow or JAX[23] for computations on GPUs. Because of its popularity, these often
implement a subset of NumPy's API or mimic it, so that users can change their array
implementation with minimal changes to their code required.[3] A library named CuPy,[24]
accelerated by Nvidia's CUDA framework, has also shown potential for faster computing,
being a 'drop-in replacement' of NumPy.[25]

Examples
NumPy is conventionally imported as np.[26]

import numpy as np
from [Link] import NDArray

a: NDArray[int] = [Link]([[1, 2, 3, 4], [3, 4, 6, 7], [5, 9, 0, 5]])


[Link]()

Basic operations

from [Link] import NDArray

a: NDArray[int] = [Link]([1, 2, 3, 6])


b: NDArray[int] = [Link](0, 2, 4) # create an array with four equally spaced points starting with 0
and ending with 2.
c: NDArray[int] = a - b
print(c)
# prints array([ 1. , 1.33333333, 1.66666667, 4. ])
print(a ** 2)
# prints array([ 1, 4, 9, 36])

Universal functions

from [Link] import NDArray, float64

a: NDArray[float64] = [Link](-[Link], [Link], 100)


b: float64 = [Link](a)
c: float64 = [Link](a)

# Functions can take both numbers and arrays as parameters.


print([Link](1))
# prints 0.8414709848078965
print([Link]([Link]([1, 2, 3])))
# prints array([0.84147098, 0.90929743, 0.14112001])

Linear algebra

import numpy as np
from [Link] import solve, inv
from [Link] import rand
from [Link] import NDArray, float32
a: NDArray[float32] = [Link]([[1, 2, 3], [3, 4, 6.7], [5, 9.0, 5]])
print([Link]())
# prints:
# array([[ 1. , 3. , 5. ],
# [ 2. , 4. , 9. ],
# [ 3. , 6.7, 5. ]])
print(inv(a))
# prints:
# array([[-2.27683616, 0.96045198, 0.07909605],
# [ 1.04519774, -0.56497175, 0.1299435 ],
# [ 0.39548023, 0.05649718, -0.11299435]])
b: NDArray[int] = [Link]([3, 2, 1])
print(solve(a, b)) # solve the equation ax = b
# prints array([-4.83050847, 2.13559322, 1.18644068])
c: NDArray[float32] = rand(3, 3) * 20 # create a 3x3 random matrix of values within [0,1] scaled by 20
print(c)
# prints:
# array([[ 3.98732789, 2.47702609, 4.71167924],
# [ 9.24410671, 5.5240412 , 10.6468792 ],
# [ 10.38136661, 8.44968437, 15.17639591]])
print([Link](a, c)) # matrix multiplication
# prints:
# array([[ 53.61964114, 38.8741616 , 71.53462537],
# [ 118.4935668 , 86.14012835, 158.40440712],
# [ 155.04043289, 104.3499231 , 195.26228855]])
print(a @ c) # Starting with Python 3.5 and NumPy 1.10
# prints:
# array([[ 53.61964114, 38.8741616 , 71.53462537],
# [ 118.4935668 , 86.14012835, 158.40440712],
# [ 155.04043289, 104.3499231 , 195.26228855]])

Multidimensional arrays

import numpy as np
from [Link] import NDArray, float64

M: NDArray[float64] = [Link](shape=(2, 3, 5, 7, 11))


T: NDArray[float64] = [Link](M, (4, 2, 1, 3, 0))
print([Link])
# prints (11, 5, 3, 7, 2)

Incorporation with OpenCV

import cv2
import numpy as np
from [Link] import NDArray, float32

r: NDArray[float32] = [Link]([Link](256*256)%256,(256,256)) # 256x256 pixel array with a


horizontal gradient from 0 to 255 for the red color channel
g: NDArray[float32] = np.zeros_like(r) # array of same size and type as r but filled with 0s for the
green color channel
b: NDArray[float32] = r.T # transposed r will give a vertical gradient for the blue color channel
print([Link]("[Link]", [Link]([b,g,r]))) # OpenCV images are interpreted as BGR, the
depth-stacked array will be written to an 8bit RGB PNG-file called "[Link]"
# prints True

Nearest-neighbor search
Functional Python and vectorized NumPy version.

### Functional Python ###


from typing import Callable

points: list[list[int]] = [[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: list[int] = [4,5,3]
# Lambda function for calculating the Euclidean distance of two vectors
edistance: Callable[[list[float], list[float]], float] = lambda a, b: sum((a1 - b1) ** 2 for a1, b1 in
zip(a, b)) ** 0.5
# Compute all Euclidean distances at once and return the nearest point
nearest: list[int] = min((edistance(i, qpoint), i) for i in points)[1]
print(f"Nearest point to q: {nearest}")
# prints Nearest point to q: [3, 4, 4]
### Equivalent NumPy vectorization ###
import numpy as np
from [Link] import NDArray

points: NDArray[int] = [Link]([[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: NDArray[int] = [Link]([4,5,3])
minIdx: int = [Link]([Link](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]}")
# prints Nearest point to q: [3 4 4]

F2PY
Quickly wrap native code for faster scripts.[27][28][29]

! 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

import foo
import numpy as np

a: tuple[int, int] = [Link](1, 2, 3) # or c,d = instead of a.c and a.d


print(a)
# prints (9,-27)
help("[Link]")
# prints the [Link].__doc__

See also
Array programming
List of numerical-analysis software
Theano (software)
Matplotlib
Fortran
Row- and column-major order
f2c

References
1. "Release 2.3.5" ([Link] 16 November 2025.
Retrieved 18 November 2025.
2. "NumPy — NumPy" ([Link] [Link]. NumPy developers.
3. Charles R Harris; K. Jarrod Millman; Stéfan J. van der Walt; et al. (16 September 2020). "Array
programming with NumPy" ([Link] (PDF).
Nature. 585 (7825): 357–362. arXiv:2006.10256 ([Link]
doi:10.1038/S41586-020-2649-2 ([Link] ISSN 1476-
4687 ([Link] PMC 7759461 ([Link]
ov/pmc/articles/PMC7759461). PMID 32939066 ([Link]
6). Wikidata Q99413970.
4. "NumFOCUS Sponsored Projects" ([Link] NumFOCUS.
Retrieved 2021-10-25.
5. "Indexing — NumPy v1.20 Manual" ([Link]
ml). [Link]. Retrieved 2021-04-06.
6. Millman, K. Jarrod; Aivazis, Michael (2011). "Python for Scientists and Engineers" ([Link]
[Link]/web/20190219031439/[Link]
[Link]). Computing in Science and Engineering. 13 (2): 9–12.
Bibcode:2011CSE....13b...9M ([Link]
doi:10.1109/MCSE.2011.36 ([Link] Archived from the
original ([Link] on 2019-02-
19. Retrieved 2014-07-07.
7. Travis Oliphant (2007). "Python for Scientific Computing" ([Link]
14035918/[Link] (PDF).
Computing in Science and Engineering. Archived from the original ([Link]
r/~thsant/pool/oliphant-python_scientific.pdf) (PDF) on 2013-10-14. Retrieved 2013-10-12.
8. David Ascher; Paul F. Dubois; Konrad Hinsen; Jim Hugunin; Travis Oliphant (1999). "Numerical
Python" ([Link] (PDF).
9. van der Walt, Stéfan; Colbert, S. Chris; Varoquaux, Gaël (2011). "The NumPy array: a structure
for efficient numerical computation". Computing in Science and Engineering. 13 (2). IEEE: 22.
arXiv:1102.1523 ([Link] Bibcode:2011CSE....13b..22V ([Link]
[Link]/abs/2011CSE....13b..22V). doi:10.1109/MCSE.2011.37 ([Link]
109%2FMCSE.2011.37). S2CID 16907816 ([Link]
6).
10. "Numarray Homepage" ([Link]
Retrieved 2006-06-24.
11. Travis E. Oliphant (7 December 2006). Guide to NumPy ([Link]
k). Retrieved 2 February 2017.
12. Travis Oliphant and other SciPy developers. "[Numpy-discussion] Status of Numeric" ([Link]
[Link]/pipermail/numpy-discussion/2004-January/[Link]). Retrieved 2 February
2017.
13. "NumPy Sourceforge Files" ([Link]
Retrieved 2008-03-24.
14. "History_of_SciPy - SciPy wiki dump" ([Link]
tml). [Link].
15. "NumPy 1.5.0 Release Notes" ([Link]
[Link]/view). Retrieved 2011-04-29.
16. "PyPy Status Blog: NumPy funding and status update" ([Link]
0/[Link]). Retrieved 2011-12-22.
17. "NumPyPy Status" ([Link] Retrieved 2023-12-19.
18. The SciPy Community. "NumPy for Matlab users" ([Link]
[Link]). Retrieved 2 February 2017.
19. "numpy release notes" ([Link]
20. McKinney, Wes (2014). "NumPy Basics: Arrays and Vectorized Computation". Python for Data
Analysis (First Edition, Third release ed.). O'Reilly. p. 79. ISBN 978-1-449-31979-3.
21. Francesc Alted. "numexpr" ([Link] GitHub. Retrieved 8 March
2014.
22. "Numba" ([Link] [Link]. Retrieved 8 March 2014.
23. Documentationː [Link] ([Link]
24. Shohei Hido - CuPy: A NumPy-compatible Library for GPU - PyCon 2018 ([Link]
m/watch?v=MAz1xolSB68), archived ([Link]
Az1xolSB68) from the original on 2021-12-21, retrieved 2021-05-11
25. Entschev, Peter Andreas (2019-07-23). "Single-GPU CuPy Speedups" ([Link]
ds-ai/single-gpu-cupy-speedups-ea99cbbb0cbb). Medium. Retrieved 2021-05-11.
26. "NumPy: the absolute basics for beginners § How to import NumPy" ([Link]
able/user/absolute_beginners.html#how-to-import-numpy). NumPy Manual. v2.3. Archived (htt
ps://[Link]/web/20250828174148/[Link]
[Link]#how-to-import-numpy) from the original on 2025-08-28. Retrieved 1 September
2025. "After installing NumPy, it may be imported into Python code like: 'import numpy as np'.
This widespread convention allows access to NumPy features [...]"
27. "F2PY docs from NumPy" ([Link]
NumPy. Retrieved 18 April 2022.
28. Worthey, Guy (3 January 2022). "A python vs. Fortran smackdown" ([Link]
2/01/03/a-python-vs-fortran-smackdown/). Guy Worthey. Retrieved 18 April 2022.
29. Shell, Scott. "Writing fast Fortran routines for Python" ([Link]
l/che210d/[Link]) (PDF). UCSB Engineering Department. University of California, Santa
Barbara. Retrieved 18 April 2022.

Further reading
McKinney, Wes (2022). Python for Data Analysis ([Link] (3rd ed.).
O'Reilly. ISBN 978-1098104030.
Bressert, Eli (2012). Scipy and Numpy: An Overview for Developers. O'Reilly. ISBN 978-1-4493-
0546-8.
VanderPlas, Jake (2016). "Introduction to NumPy". Python Data Science Handbook: Essential
Tools for Working with Data. O'Reilly. pp. 33–96. ISBN 978-1-4919-1205-8.

External links
Official website ([Link]
NumPy tutorials ([Link]
History of NumPy ([Link]

Retrieved from "[Link]

Common questions

Powered by AI

NumPy serves as a foundational library for scientific computing due to its robust implementation of n-dimensional arrays and efficient computational methods, providing a base for libraries like SciPy, Pandas, and Matplotlib. This integration allows higher-level operations and complex analyses to be built upon its foundation, facilitating widespread adoption among developers who benefit from a consistent and optimized framework. Its foundational role has promoted NumPy as an indispensable tool in scientific computing .

NumPy facilitates integration with other programming languages and libraries by providing a C API for interoperability with low-level languages, as well as allowing its arrays to serve as views into memory buffers allocated by C, C++, Python, and Fortran. This compatibility enables NumPy to work with existing numerical libraries such as BLAS and LAPACK and simplifies the integration with Python extensions that require efficient numeric operations without data duplication .

The creation of NumPy was motivated by the need to unify the community around a single array package for numerical computing, initially inspired by the limitations of Python's numerical capabilities. NumPy evolved from its predecessors, Numeric and Numarray, by incorporating the best features from both while resolving their limitations. Travis Oliphant spearheaded the development of NumPy in 2005 through extensive modifications, effectively creating NumPy 1.0 in 2006 as a part of the SciPy library .

Both MATLAB and NumPy support linear algebra computations and rely on libraries such as BLAS and LAPACK for efficient execution. They allow vectorized operations for fast computation. However, MATLAB offers a broader selection of toolboxes and specialized tools like Simulink, whereas NumPy benefits from the extensive ecosystem of Python, offering flexibility through integration with other Python libraries. NumPy requires external libraries like scipy.sparse for sparse matrix operations, which are natively supported in MATLAB .

In image processing, NumPy offers efficient storage and manipulation of image data by representing images as multidimensional arrays. This compatibility is critical for OpenCV, which uses NumPy arrays for operations like indexing and transformations. The advantages include ease of integration and simplified coding for complex operations. However, NumPy's limitations in handling sparse data and parallel processing without additional libraries can pose challenges for large-scale or real-time processing tasks .

NumPy's approach to memory management involves using contiguous memory blocks for its arrays, which reduces overhead from memory allocation and improves cache efficiency during computations. This strategy leads to faster execution of operations compared to using Python lists, which are non-contiguous and dynamically allocated. NumPy's memory-mapped ndarrays and ability to interact with memory buffers allocated by other languages such as C and Fortran further contribute to performance by avoiding unnecessary data copying .

NumPy addresses the Global Interpreter Lock (GIL) issue by releasing the GIL during many of its internal C operations, particularly those involving array computations. This approach allows Python threads to perform multi-threaded processing, bypassing one of Python's significant constraints on concurrent execution. It enhances performance in multi-threaded applications where NumPy operations form a bottleneck by enabling parallel execution .

Array vectorization in NumPy allows operations on entire arrays at once, rather than element-by-element, leading to significant improvements in computational speed. This approach leverages underlying C and Fortran routines, reducing the overhead of Python loops, which are slower due to the interpreter's operation. Vectorization results in concise code and optimizes data handling, particularly for large datasets, contributing to its widespread use in numerical computing .

NumPy faces challenges in large-scale scientific computing as its arrays are typically loaded into a single computer's memory, making it difficult to handle very large datasets. Additionally, NumPy operations are executed on a single CPU unless explicitly parallelized. Alternative solutions like Dask and TensorFlow provide scalable array operations that can be distributed across computer clusters or executed on GPUs, addressing NumPy's limitations in memory and parallel processing. These alternatives often mimic NumPy's API, allowing users to transition with minimal code changes .

NumPy improves computational efficiency in Python by providing multidimensional arrays and functions that allow operations to be performed on entire arrays rather than element-by-element. This vectorized approach is faster than using Python's built-in lists, which are not optimized for numerical operations. Additionally, NumPy's arrays are homogeneously typed and utilize contiguous memory blocks, further enhancing performance compared to dynamically-typed and non-contiguous list data structures .

You might also like