updated August 27, 2019
NumPy Array cheatsheet
NumPy Python library provides custom array data type that supports standard array functionality like indexing and slicing but works differently in arithmetic operations: performs them on each array element
Element-wise arithmetic operations
You can perform the same operation on each element: add the same number or multiply by the same number:>>> import numpy as np >>> arr = np.array([1, 2, 3]) >>> arr array([1, 2, 3]) >>> arr + 10 array([11, 12, 13]) >>> arr * 2 array([2, 4, 6])or sum two arrays of same dimensionality:
>>> arr + np.array([10, 20, 30]) array([11, 22, 33])or calculate the value from the all array elements:
>>> np.mean(arr) 2.0 >>> np.std(arr) # standard deviation 0.816496580927726You have to use comprehension or
for
loop with standard array for such calculations:
>>> arr = [1, 2, 3] >>> [e * 2 for e in arr] [2, 4, 6]or even more complex to sum two arrays:
>>> a = [1, 2, 3] >>> b = [10, 20, 30] >>> [x+y for x, y in zip(a, b)] [11, 22, 33]
Indexing in different way
Getting element for many-dimensional array:>>> a = [[1, 2, 3], [11, 12, 13]] >>> arr = np.array([[1, 2, 3], [11, 12, 13]]) # 2 rows, 3 columns >>> arr.shape # array dimensionality (2, 3) >>> a[1][2] 13 >>> arr[1][2] 13 >>> arr[1,2] # tuple indexing 13also NumPy array provides column slicing as well, with tuple indexing with slicing on row index:
>>> arr[:,1] array([ 2, 12])