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 2021-2022

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 2021-2022

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 2021-2022

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] 100 loops, best of 3: 18.4 ms per loop In [4]: b = np.arange(L) In [5]: %timeit b**2 The slowest run took 11.81 times longer than the f astest. This could mean that an intermediate resul t is being cached. 10000 loops, best of 3: 35.9 ?s per loop

Lab Calc 2021-2022

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 2021-2022

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 2021-2022

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 2021-2022

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download