NumPy: Array Manipulation
[Pages:34]NumPy: Array Manipulation
Hendrik Speleers
NumPy: Array Manipulation
Overview
? 1D and 2D arrays
Creation, indexing and slicing Memory structure
? Shape manipulation ? Basic mathematical operations
Arithmetic and logic operations Reduction and linear algebra operations
? Other operations
Polynomial manipulation Input and output
Lab Calc 2023-2024
NumPy: Array Manipulation
NumPy
? Numerical Python ? Python extension for multi-dimensional arrays
Suited for creation and manipulation of numerical data Closer to hardware: more efficient Designed for scientific computation: more intuitive
? Import convention
import numpy as np
Lab Calc 2023-2024
NumPy: Array Manipulation
NumPy array
? A NumPy array is a collection of objects of the same type
In [1]: a = np.array([0, 1, 2, 3]) In [2]: a Out[2]: array([0, 1, 2, 3]) In [3]: a.size Out[3]: 4
? Default object types of an array
boolean (bool), integer (int, int64) float (float, float64), complex (complex, complex128)
Lab Calc 2023-2024
NumPy: Array Manipulation
NumPy array
? More compact and more efficient operations than list
In [1]: L = 100000 In [2]: a = range(L) In [3]: %timeit [i**2 for i in a] 16.4 ms ? 8.6 ?s per loop (mean ? std. dev. of 7 runs, 100 loops each) In [4]: b = np.arange(L) In [5]: %timeit b**2 33.7 ?s ? 43.4 ns per loop (mean ? std. dev. of 7 runs, 10000 loops each)
Lab Calc 2023-2024
NumPy: Array Manipulation
1D array: creation
? Manual creation
In [1]: a = np.array([1, 2, 3]) ...: a.dtype
Out[1]: dtype('int64') In [2]: a = np.array([1.0, 2.0, 3.0])
...: a.dtype Out[2]: dtype('float64') In [3]: a = np.array([1, 2, 3], dtype='float64')
...: a.dtype Out[3]: dtype('float64')
Lab Calc 2023-2024
NumPy: Array Manipulation
1D array: creation
? Evenly spaced arrays
np.arange(start, stop, step, dtype=None) np.linspace(start, stop, num=50, endpoint=True, dtype=None)
? Common arrays
np.zeros(N, dtype=None), np.ones(N, dtype=None) np.full(N, value, dtype=None)
? Arrays with random numbers
Uniform distribution: np.random.rand(N) Gaussian distribution: np.random.randn(N)
Lab Calc 2023-2024
NumPy: Array Manipulation
1D array: indexing
? Slicing syntax similar to lists
In [1]: a = np.arange(10) In [2]: a[0], a[1], a[-1] Out[2]: (0, 1, 9) In [3]: a[3:6] Out[3]: array([3, 4, 5]) In [4]: a[::-1] Out[4]: array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) In [5]: b = a[6:8] In [6]: b Out[6]: array([6, 7])
Lab Calc 2023-2024
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.