Solutions¶
1. Import the numpy package under the name np (★☆☆)¶
In [1]:
Copied!
import numpy as np
import numpy as np
2. Print the numpy version and the configuration (★☆☆)¶
In [2]:
Copied!
print(np.__version__)
np.show_config()
print(np.__version__)
np.show_config()
1.22.4
openblas64__info:
library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas64__info']
libraries = ['openblas64__info']
language = f77
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None)]
blas_ilp64_opt_info:
library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas64__info']
libraries = ['openblas64__info']
language = f77
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None)]
openblas64__lapack_info:
library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas64__lapack_info']
libraries = ['openblas64__lapack_info']
language = f77
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)]
lapack_ilp64_opt_info:
library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas64__lapack_info']
libraries = ['openblas64__lapack_info']
language = f77
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)]
Supported SIMD extensions in this NumPy install:
baseline = SSE,SSE2,SSE3
found = SSSE3,SSE41,POPCNT,SSE42,AVX,F16C,FMA3,AVX2,AVX512F,AVX512CD,AVX512_SKX,AVX512_CLX,AVX512_CNL
not found =
3. Create a null vector of size 10 (★☆☆)¶
In [3]:
Copied!
Z = np.zeros(10)
print(Z)
Z = np.zeros(10)
print(Z)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
4. How to find the memory size of any array (★☆☆)¶
In [4]:
Copied!
Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))
Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))
800 bytes
5. How to get the documentation of the numpy add function from the command line? (★☆☆)¶
In [5]:
Copied!
np.info(np.add)
np.info(np.add)
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
add : ndarray or scalar
The sum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.
Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
The ``+`` operator can be used as a shorthand for ``np.add`` on ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 + x2
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)¶
In [6]:
Copied!
Z = np.zeros(10)
Z[4] = 1
print(Z)
Z = np.zeros(10)
Z[4] = 1
print(Z)
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
7. Create a vector with values ranging from 10 to 49 (★☆☆)¶
In [7]:
Copied!
Z = np.arange(10,50)
print(Z)
Z = np.arange(10,50)
print(Z)
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]
8. Reverse a vector (first element becomes last) (★☆☆)¶
In [8]:
Copied!
Z = np.arange(50)
Z = Z[::-1]
print(Z)
Z = np.arange(50)
Z = Z[::-1]
print(Z)
[49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0]
9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)¶
In [9]:
Copied!
Z = np.arange(9).reshape(3, 3)
print(Z)
Z = np.arange(9).reshape(3, 3)
print(Z)
[[0 1 2] [3 4 5] [6 7 8]]
10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)¶
In [10]:
Copied!
nz = np.nonzero([1,2,0,0,4,0])
print(nz)
nz = np.nonzero([1,2,0,0,4,0])
print(nz)
(array([0, 1, 4], dtype=int64),)
11. Create a 3x3 identity matrix (★☆☆)¶
In [11]:
Copied!
Z = np.eye(3)
print(Z)
Z = np.eye(3)
print(Z)
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
12. Create a 3x3x3 array with random values (★☆☆)¶
In [12]:
Copied!
Z = np.random.random((3,3,3))
print(Z)
Z = np.random.random((3,3,3))
print(Z)
[[[0.18706586 0.31744639 0.01849506] [0.47050903 0.34210448 0.96753514] [0.66980685 0.21293508 0.16617303]] [[0.87272712 0.49187371 0.03470095] [0.97153163 0.3771096 0.42540491] [0.24080208 0.62207831 0.88409107]] [[0.89147529 0.86930826 0.91745154] [0.04693251 0.2329456 0.55805096] [0.56213661 0.53077455 0.74548484]]]
13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)¶
In [13]:
Copied!
Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
0.0033314487054991737 0.9959546668808226
14. Create a random vector of size 30 and find the mean value (★☆☆)¶
In [14]:
Copied!
Z = np.random.random(30)
m = Z.mean()
print(m)
Z = np.random.random(30)
m = Z.mean()
print(m)
0.5350759835722315
15. Create a 2d array with 1 on the border and 0 inside (★☆☆)¶
In [15]:
Copied!
Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
print(Z)
Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
print(Z)
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]
16. How to add a border (filled with 0's) around an existing array? (★☆☆)¶
In [16]:
Copied!
Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
# Using fancy indexing
Z[:, [0, -1]] = 0
Z[[0, -1], :] = 0
print(Z)
Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
# Using fancy indexing
Z[:, [0, -1]] = 0
Z[[0, -1], :] = 0
print(Z)
[[0. 0. 0. 0. 0. 0. 0.] [0. 1. 1. 1. 1. 1. 0.] [0. 1. 1. 1. 1. 1. 0.] [0. 1. 1. 1. 1. 1. 0.] [0. 1. 1. 1. 1. 1. 0.] [0. 1. 1. 1. 1. 1. 0.] [0. 0. 0. 0. 0. 0. 0.]] [[0. 0. 0. 0. 0. 0. 0.] [0. 1. 1. 1. 1. 1. 0.] [0. 1. 1. 1. 1. 1. 0.] [0. 1. 1. 1. 1. 1. 0.] [0. 1. 1. 1. 1. 1. 0.] [0. 1. 1. 1. 1. 1. 0.] [0. 0. 0. 0. 0. 0. 0.]]
17. What is the result of the following expression? (★☆☆)¶
0 * np.nan
np.nan == np.nan
np.inf > np.nan
np.nan - np.nan
np.nan in set([np.nan])
0.3 == 3 * 0.1
In [17]:
Copied!
print(0 * np.nan)
print(np.nan == np.nan)
print(np.inf > np.nan)
print(np.nan - np.nan)
print(np.nan in set([np.nan]))
print(0.3 == 3 * 0.1)
print(0 * np.nan)
print(np.nan == np.nan)
print(np.inf > np.nan)
print(np.nan - np.nan)
print(np.nan in set([np.nan]))
print(0.3 == 3 * 0.1)
nan False False nan True False
18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)¶
In [18]:
Copied!
Z = np.diag(1+np.arange(4),k=-1)
print(Z)
Z = np.diag(1+np.arange(4),k=-1)
print(Z)
[[0 0 0 0 0] [1 0 0 0 0] [0 2 0 0 0] [0 0 3 0 0] [0 0 0 4 0]]
19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)¶
In [19]:
Copied!
Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
[[0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0]]
20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆)¶
In [20]:
Copied!
print(np.unravel_index(99,(6,7,8)))
print(np.unravel_index(99,(6,7,8)))
(1, 5, 3)
21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)¶
In [21]:
Copied!
Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(Z)
Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(Z)
[[0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0]]
22. Normalize a 5x5 random matrix (★☆☆)¶
In [22]:
Copied!
Z = np.random.random((5,5))
Z = (Z - np.mean (Z)) / (np.std (Z))
print(Z)
Z = np.random.random((5,5))
Z = (Z - np.mean (Z)) / (np.std (Z))
print(Z)
[[ 0.82192864 -0.85230453 -0.52210189 -0.45231069 2.00410038] [-0.06103306 1.80884174 -0.47221316 -1.22565347 -0.40278046] [-0.878112 0.64334824 -0.90327146 -1.31630779 1.73975974] [-0.59067317 -1.38590411 -0.1090274 -0.49058768 0.2755492 ] [ 1.90208071 0.35808221 0.25615234 -0.69033668 0.54277436]]
23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)¶
In [23]:
Copied!
color = np.dtype([("r", np.ubyte),
("g", np.ubyte),
("b", np.ubyte),
("a", np.ubyte)])
color = np.dtype([("r", np.ubyte),
("g", np.ubyte),
("b", np.ubyte),
("a", np.ubyte)])
24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)¶
In [24]:
Copied!
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
# Alternative solution, in Python 3.5 and above
Z = np.ones((5,3)) @ np.ones((3,2))
print(Z)
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
# Alternative solution, in Python 3.5 and above
Z = np.ones((5,3)) @ np.ones((3,2))
print(Z)
[[3. 3.] [3. 3.] [3. 3.] [3. 3.] [3. 3.]] [[3. 3.] [3. 3.] [3. 3.] [3. 3.] [3. 3.]]
25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)¶
In [25]:
Copied!
# Author: Evgeni Burovski
Z = np.arange(11)
Z[(3 < Z) & (Z < 8)] *= -1
print(Z)
# Author: Evgeni Burovski
Z = np.arange(11)
Z[(3 < Z) & (Z < 8)] *= -1
print(Z)
[ 0 1 2 3 -4 -5 -6 -7 8 9 10]
26. What is the output of the following script? (★☆☆)¶
# Author: Jake VanderPlas
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
In [26]:
Copied!
# Author: Jake VanderPlas
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
# Author: Jake VanderPlas
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
9 10
27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)¶
Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z
In [27]:
Copied!
# Create an integer vector Z
Z = np.array([2, 3, 4])
# Legal Expressions:
# 1. Exponentiation of each element in Z to itself
result1 = Z ** Z
print("Result 1:", result1)
# 2. Bitwise left shift by Z and then right shift by 2
result2 = 2 << Z >> 2
print("Result 2:", result2)
# 3. Element-wise comparison of Z with -Z
result3 = Z < -Z
print("Result 3:", result3)
# 4. Multiplying each element in Z by 1j (complex unit)
result4 = 1j * Z
print("Result 4:", result4)
# 5. Division of each element in Z by 1 and then by 1 again
result5 = Z / 1 / 1
print("Result 5:", result5)
# 6. Illegal Expression: Comparison of Z with Z and then with Z again
# result6 = Z < Z > Z # This expression is not clear and will result in a syntax error
# Create an integer vector Z
Z = np.array([2, 3, 4])
# Legal Expressions:
# 1. Exponentiation of each element in Z to itself
result1 = Z ** Z
print("Result 1:", result1)
# 2. Bitwise left shift by Z and then right shift by 2
result2 = 2 << Z >> 2
print("Result 2:", result2)
# 3. Element-wise comparison of Z with -Z
result3 = Z < -Z
print("Result 3:", result3)
# 4. Multiplying each element in Z by 1j (complex unit)
result4 = 1j * Z
print("Result 4:", result4)
# 5. Division of each element in Z by 1 and then by 1 again
result5 = Z / 1 / 1
print("Result 5:", result5)
# 6. Illegal Expression: Comparison of Z with Z and then with Z again
# result6 = Z < Z > Z # This expression is not clear and will result in a syntax error
Result 1: [ 4 27 256] Result 2: [2 4 8] Result 3: [False False False] Result 4: [0.+2.j 0.+3.j 0.+4.j] Result 5: [2. 3. 4.]
28. What are the result of the following expressions? (★☆☆)¶
np.array(0) / np.array(0)
np.array(0) // np.array(0)
np.array([np.nan]).astype(int).astype(float)
In [28]:
Copied!
print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float))
print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float))
nan 0 [-2.14748365e+09]
C:\Users\franc\AppData\Local\Temp\ipykernel_22896\3912170336.py:1: RuntimeWarning: invalid value encountered in true_divide print(np.array(0) / np.array(0)) C:\Users\franc\AppData\Local\Temp\ipykernel_22896\3912170336.py:2: RuntimeWarning: divide by zero encountered in floor_divide print(np.array(0) // np.array(0))
29. How to round away from zero a float array ? (★☆☆)¶
In [29]:
Copied!
# Author: Charles R Harris
Z = np.random.uniform(-10,+10,10)
print(np.copysign(np.ceil(np.abs(Z)), Z))
# More readable but less efficient
print(np.where(Z>0, np.ceil(Z), np.floor(Z)))
# Author: Charles R Harris
Z = np.random.uniform(-10,+10,10)
print(np.copysign(np.ceil(np.abs(Z)), Z))
# More readable but less efficient
print(np.where(Z>0, np.ceil(Z), np.floor(Z)))
[ -2. 3. 6. 5. 3. -6. -9. 5. 8. -10.] [ -2. 3. 6. 5. 3. -6. -9. 5. 8. -10.]
30. How to find common values between two arrays? (★☆☆)¶
In [30]:
Copied!
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))
[0 2 3 8]
31. How to ignore all numpy warnings (not recommended)? (★☆☆)¶
In [31]:
Copied!
# Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0
# Back to sanity
_ = np.seterr(**defaults)
# Equivalently with a context manager
with np.errstate(all="ignore"):
np.arange(3) / 0
# Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0
# Back to sanity
_ = np.seterr(**defaults)
# Equivalently with a context manager
with np.errstate(all="ignore"):
np.arange(3) / 0
32. Is the following expressions true? (★☆☆)¶
np.sqrt(-1) == np.emath.sqrt(-1)
In [32]:
Copied!
np.sqrt(-1) == np.emath.sqrt(-1)
np.sqrt(-1) == np.emath.sqrt(-1)
C:\Users\franc\AppData\Local\Temp\ipykernel_22896\244602691.py:1: RuntimeWarning: invalid value encountered in sqrt np.sqrt(-1) == np.emath.sqrt(-1)
Out[32]:
False
33. How to get the dates of yesterday, today and tomorrow? (★☆☆)¶
In [33]:
Copied!
yesterday = np.datetime64('today') - np.timedelta64(1)
today = np.datetime64('today')
tomorrow = np.datetime64('today') + np.timedelta64(1)
yesterday = np.datetime64('today') - np.timedelta64(1)
today = np.datetime64('today')
tomorrow = np.datetime64('today') + np.timedelta64(1)
34. How to get all the dates corresponding to the month of July 2016? (★★☆)¶
In [34]:
Copied!
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)
['2016-07-01' '2016-07-02' '2016-07-03' '2016-07-04' '2016-07-05' '2016-07-06' '2016-07-07' '2016-07-08' '2016-07-09' '2016-07-10' '2016-07-11' '2016-07-12' '2016-07-13' '2016-07-14' '2016-07-15' '2016-07-16' '2016-07-17' '2016-07-18' '2016-07-19' '2016-07-20' '2016-07-21' '2016-07-22' '2016-07-23' '2016-07-24' '2016-07-25' '2016-07-26' '2016-07-27' '2016-07-28' '2016-07-29' '2016-07-30' '2016-07-31']
35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)¶
In [35]:
Copied!
A = np.ones(3)*1
B = np.ones(3)*2
np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)
A = np.ones(3)*1
B = np.ones(3)*2
np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)
Out[35]:
array([-1.5, -1.5, -1.5])
36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)¶
In [36]:
Copied!
Z = np.random.uniform(0,10,10)
print(Z - Z%1)
print(Z // 1)
print(np.floor(Z))
print(Z.astype(int))
print(np.trunc(Z))
Z = np.random.uniform(0,10,10)
print(Z - Z%1)
print(Z // 1)
print(np.floor(Z))
print(Z.astype(int))
print(np.trunc(Z))
[9. 2. 4. 8. 5. 1. 9. 0. 7. 9.] [9. 2. 4. 8. 5. 1. 9. 0. 7. 9.] [9. 2. 4. 8. 5. 1. 9. 0. 7. 9.] [9 2 4 8 5 1 9 0 7 9] [9. 2. 4. 8. 5. 1. 9. 0. 7. 9.]
37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)¶
In [37]:
Copied!
Z = np.zeros((5,5))
Z += np.arange(5)
print(Z)
# without broadcasting
Z = np.tile(np.arange(0, 5), (5,1))
print(Z)
Z = np.zeros((5,5))
Z += np.arange(5)
print(Z)
# without broadcasting
Z = np.tile(np.arange(0, 5), (5,1))
print(Z)
[[0. 1. 2. 3. 4.] [0. 1. 2. 3. 4.] [0. 1. 2. 3. 4.] [0. 1. 2. 3. 4.] [0. 1. 2. 3. 4.]] [[0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4]]
38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)¶
In [38]:
Copied!
def generate():
for x in range(10):
yield x
Z = np.fromiter(generate(),dtype=float,count=-1)
print(Z)
def generate():
for x in range(10):
yield x
Z = np.fromiter(generate(),dtype=float,count=-1)
print(Z)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)¶
In [39]:
Copied!
Z = np.linspace(0,1,11,endpoint=False)[1:]
print(Z)
Z = np.linspace(0,1,11,endpoint=False)[1:]
print(Z)
[0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455 0.63636364 0.72727273 0.81818182 0.90909091]
40. Create a random vector of size 10 and sort it (★★☆)¶
In [40]:
Copied!
Z = np.random.random(10)
Z.sort()
print(Z)
Z = np.random.random(10)
Z.sort()
print(Z)
[0.09562659 0.29963627 0.3293784 0.40679516 0.43882945 0.55310042 0.62305481 0.63314441 0.98141974 0.98540289]
41. How to sum a small array faster than np.sum? (★★☆)¶
In [41]:
Copied!
# Author: Evgeni Burovski
Z = np.arange(10)
np.add.reduce(Z)
# Author: Evgeni Burovski
Z = np.arange(10)
np.add.reduce(Z)
Out[41]:
45
42. Consider two random array A and B, check if they are equal (★★☆)¶
In [42]:
Copied!
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(A,B)
print(equal)
# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = np.array_equal(A,B)
print(equal)
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(A,B)
print(equal)
# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = np.array_equal(A,B)
print(equal)
False False
43. Make an array immutable (read-only) (★★☆)¶
In [43]:
Copied!
Z = np.zeros(10)
Z.flags.writeable = False
# Z[0] = 1 output: ValueError: assignment destination is read-only
Z = np.zeros(10)
Z.flags.writeable = False
# Z[0] = 1 output: ValueError: assignment destination is read-only
44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)¶
In [44]:
Copied!
Z = np.random.random((10,2))
X,Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2+Y**2)
T = np.arctan2(Y,X)
print(R)
print(T)
Z = np.random.random((10,2))
X,Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2+Y**2)
T = np.arctan2(Y,X)
print(R)
print(T)
[0.81412643 1.20152264 0.68283666 0.61657335 0.80002848 0.9335422 1.27652783 0.81503993 0.94751177 0.37569658] [0.89558263 0.80565148 0.34224313 0.06255344 1.55547358 1.00102971 0.73106547 1.49524721 0.22656445 0.23360572]
45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)¶
In [45]:
Copied!
Z = np.random.random(10)
Z[Z.argmax()] = 0
print(Z)
Z = np.random.random(10)
Z[Z.argmax()] = 0
print(Z)
[0.45363248 0.58060745 0.23004142 0.30939965 0.40415269 0.67037438 0.32700314 0.34156142 0.18548905 0. ]
46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)¶
In [46]:
Copied!
Z = np.zeros((5,5), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
np.linspace(0,1,5))
print(Z)
Z = np.zeros((5,5), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
np.linspace(0,1,5))
print(Z)
[[(0. , 0. ) (0.25, 0. ) (0.5 , 0. ) (0.75, 0. ) (1. , 0. )] [(0. , 0.25) (0.25, 0.25) (0.5 , 0.25) (0.75, 0.25) (1. , 0.25)] [(0. , 0.5 ) (0.25, 0.5 ) (0.5 , 0.5 ) (0.75, 0.5 ) (1. , 0.5 )] [(0. , 0.75) (0.25, 0.75) (0.5 , 0.75) (0.75, 0.75) (1. , 0.75)] [(0. , 1. ) (0.25, 1. ) (0.5 , 1. ) (0.75, 1. ) (1. , 1. )]]
47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)¶
In [47]:
Copied!
# Author: Evgeni Burovski
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
# Author: Evgeni Burovski
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
3638.163637117973
48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)¶
In [48]:
Copied!
for dtype in [np.int8, np.int32, np.int64]:
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps)
for dtype in [np.int8, np.int32, np.int64]:
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps)
-128 127 -2147483648 2147483647 -9223372036854775808 9223372036854775807 -3.4028235e+38 3.4028235e+38 1.1920929e-07 -1.7976931348623157e+308 1.7976931348623157e+308 2.220446049250313e-16
49. How to print all the values of an array? (★★☆)¶
In [49]:
Copied!
np.set_printoptions(threshold=float("inf"))
Z = np.zeros((40,40))
print(Z)
np.set_printoptions(threshold=float("inf"))
Z = np.zeros((40,40))
print(Z)
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]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0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
50. How to find the closest value (to a given scalar) in a vector? (★★☆)¶
In [50]:
Copied!
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print(Z[index])
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print(Z[index])
8
51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)¶
In [51]:
Copied!
Z = np.zeros(10, [ ('position', [ ('x', float, 1),
('y', float, 1)]),
('color', [ ('r', float, 1),
('g', float, 1),
('b', float, 1)])])
print(Z)
Z = np.zeros(10, [ ('position', [ ('x', float, 1),
('y', float, 1)]),
('color', [ ('r', float, 1),
('g', float, 1),
('b', float, 1)])])
print(Z)
[((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))]
C:\Users\franc\AppData\Local\Temp\ipykernel_22896\274409719.py:1: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
Z = np.zeros(10, [ ('position', [ ('x', float, 1),
52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)¶
In [52]:
Copied!
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0], Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)
# Much faster with scipy
import scipy
# Thanks Gavin Heverly-Coulson (#issue 1)
import scipy.spatial
Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0], Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)
# Much faster with scipy
import scipy
# Thanks Gavin Heverly-Coulson (#issue 1)
import scipy.spatial
Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)
[[0. 0.39589862 0.42323796 0.57196238 0.51834617 0.50622655 0.42192358 0.36172267 0.63403725 0.47912719] [0.39589862 0. 0.81171087 0.92645439 0.83802721 0.70523032 0.78690137 0.07322359 1.00062625 0.75591949] [0.42323796 0.81171087 0. 0.21883681 0.49880158 0.67829095 0.11892798 0.76607423 0.43895379 0.55879621] [0.57196238 0.92645439 0.21883681 0. 0.7150583 0.89503547 0.15168626 0.86914245 0.62708558 0.77761398] [0.51834617 0.83802721 0.49880158 0.7150583 0. 0.26780789 0.60396814 0.83425974 0.22513472 0.12122139] [0.50622655 0.70523032 0.67829095 0.89503547 0.26780789 0. 0.75943248 0.72394121 0.49276425 0.148577 ] [0.42192358 0.78690137 0.11892798 0.15168626 0.60396814 0.75943248 0. 0.73325893 0.55764748 0.6516632 ] [0.36172267 0.07322359 0.76607423 0.86914245 0.83425974 0.72394121 0.73325893 0. 0.98395907 0.76069106] [0.63403725 1.00062625 0.43895379 0.62708558 0.22513472 0.49276425 0.55764748 0.98395907 0. 0.34610007] [0.47912719 0.75591949 0.55879621 0.77761398 0.12122139 0.148577 0.6516632 0.76069106 0.34610007 0. ]] [[0. 0.51662719 0.28690321 0.34381315 0.25581573 0.5417461 0.51076254 0.25366387 0.43254412 0.52945729] [0.51662719 0. 0.65420995 0.40671912 0.31908387 0.49764334 0.13216788 0.76464429 0.48522876 0.32203249] [0.28690321 0.65420995 0. 0.6183857 0.33547471 0.81883981 0.70037177 0.27105849 0.30487039 0.50658745] [0.34381315 0.40671912 0.6183857 0. 0.39547647 0.20048486 0.31418021 0.56728538 0.6474858 0.61926346] [0.25581573 0.31908387 0.33547471 0.39547647 0. 0.57994074 0.37218828 0.4722725 0.25241398 0.27684618] [0.5417461 0.49764334 0.81883981 0.20048486 0.57994074 0. 0.37200985 0.75129759 0.83161576 0.76973405] [0.51076254 0.13216788 0.70037177 0.31418021 0.37218828 0.37200985 0. 0.76442641 0.58076433 0.44487025] [0.25366387 0.76464429 0.27105849 0.56728538 0.4722725 0.75129759 0.76442641 0. 0.55351742 0.71772893] [0.43254412 0.48522876 0.30487039 0.6474858 0.25241398 0.83161576 0.58076433 0.55351742 0. 0.22791003] [0.52945729 0.32203249 0.50658745 0.61926346 0.27684618 0.76973405 0.44487025 0.71772893 0.22791003 0. ]]
53. How to convert a float (32 bits) array into an integer (32 bits) in place?¶
In [53]:
Copied!
# Thanks Vikas (https://stackoverflow.com/a/10622758/5989906)
# & unutbu (https://stackoverflow.com/a/4396247/5989906)
Z = (np.random.rand(10)*100).astype(np.float32)
Y = Z.view(np.int32)
Y[:] = Z
print(Y)
# Thanks Vikas (https://stackoverflow.com/a/10622758/5989906)
# & unutbu (https://stackoverflow.com/a/4396247/5989906)
Z = (np.random.rand(10)*100).astype(np.float32)
Y = Z.view(np.int32)
Y[:] = Z
print(Y)
[60 92 69 73 59 79 90 8 62 68]
54. How to read the following file? (★★☆)¶
1, 2, 3, 4, 5
6, , , 7, 8
, , 9,10,11
In [54]:
Copied!
from io import StringIO
# Fake file
s = StringIO('''1, 2, 3, 4, 5
6, , , 7, 8
, , 9,10,11
''')
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
print(Z)
from io import StringIO
# Fake file
s = StringIO('''1, 2, 3, 4, 5
6, , , 7, 8
, , 9,10,11
''')
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
print(Z)
[[ 1 2 3 4 5] [ 6 -1 -1 7 8] [-1 -1 9 10 11]]
C:\Users\franc\AppData\Local\Temp\ipykernel_22896\1868410621.py:10: DeprecationWarning: `np.int` is a deprecated alias for the builtin `int`. To silence this warning, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
55. What is the equivalent of enumerate for numpy arrays? (★★☆)¶
In [55]:
Copied!
Z = np.arange(9).reshape(3,3)
for index, value in np.ndenumerate(Z):
print(index, value)
for index in np.ndindex(Z.shape):
print(index, Z[index])
Z = np.arange(9).reshape(3,3)
for index, value in np.ndenumerate(Z):
print(index, value)
for index in np.ndindex(Z.shape):
print(index, Z[index])
(0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 0) 3 (1, 1) 4 (1, 2) 5 (2, 0) 6 (2, 1) 7 (2, 2) 8 (0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 0) 3 (1, 1) 4 (1, 2) 5 (2, 0) 6 (2, 1) 7 (2, 2) 8
56. Generate a generic 2D Gaussian-like array (★★☆)¶
In [56]:
Copied!
Z = np.arange(9).reshape(3,3)
for index, value in np.ndenumerate(Z):
print(index, value)
for index in np.ndindex(Z.shape):
print(index, Z[index])
Z = np.arange(9).reshape(3,3)
for index, value in np.ndenumerate(Z):
print(index, value)
for index in np.ndindex(Z.shape):
print(index, Z[index])
(0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 0) 3 (1, 1) 4 (1, 2) 5 (2, 0) 6 (2, 1) 7 (2, 2) 8 (0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 0) 3 (1, 1) 4 (1, 2) 5 (2, 0) 6 (2, 1) 7 (2, 2) 8
57. How to randomly place p elements in a 2D array? (★★☆)¶
In [57]:
Copied!
# Author: Divakar
n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
print(Z)
# Author: Divakar
n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
print(Z)
[[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 1. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
58. Subtract the mean of each row of a matrix (★★☆)¶
In [58]:
Copied!
# Author: Warren Weckesser
X = np.random.rand(5, 10)
# Recent versions of numpy
Y = X - X.mean(axis=1, keepdims=True)
# Older versions of numpy
Y = X - X.mean(axis=1).reshape(-1, 1)
print(Y)
# Author: Warren Weckesser
X = np.random.rand(5, 10)
# Recent versions of numpy
Y = X - X.mean(axis=1, keepdims=True)
# Older versions of numpy
Y = X - X.mean(axis=1).reshape(-1, 1)
print(Y)
[[ 0.32987137 0.00868973 0.26345555 0.44799479 -0.15502015 -0.0658759 0.34969167 -0.21966886 -0.45523589 -0.50390232] [ 0.43294426 -0.18300281 -0.2626422 -0.27220241 -0.31989886 0.35513019 -0.44987052 0.3635884 0.07762557 0.25832837] [ 0.1163732 -0.19602846 -0.50450028 0.04255207 0.09297572 0.12947284 0.42006162 -0.11721548 -0.09888115 0.11518992] [ 0.47164075 -0.26784445 -0.19125561 -0.31440859 -0.2105185 0.30481474 0.01729134 0.03675277 0.36552895 -0.21200142] [-0.16706222 0.05028029 0.13921589 -0.37152516 0.37306672 0.16523027 0.11810213 -0.2409639 0.03898267 -0.1053267 ]]
59. How to sort an array by the nth column? (★★☆)¶
In [59]:
Copied!
# Author: Steve Tjoa
Z = np.random.randint(0,10,(3,3))
print(Z)
print(Z[Z[:,1].argsort()])
# Author: Steve Tjoa
Z = np.random.randint(0,10,(3,3))
print(Z)
print(Z[Z[:,1].argsort()])
[[5 4 2] [1 1 5] [5 5 9]] [[1 1 5] [5 4 2] [5 5 9]]
60. How to tell if a given 2D array has null columns? (★★☆)¶
In [60]:
Copied!
# Author: Warren Weckesser
# null : 0
Z = np.random.randint(0,3,(3,10))
print((~Z.any(axis=0)).any())
# null : np.nan
Z=np.array([
[0,1,np.nan],
[1,2,np.nan],
[4,5,np.nan]
])
print(np.isnan(Z).all(axis=0))
# Author: Warren Weckesser
# null : 0
Z = np.random.randint(0,3,(3,10))
print((~Z.any(axis=0)).any())
# null : np.nan
Z=np.array([
[0,1,np.nan],
[1,2,np.nan],
[4,5,np.nan]
])
print(np.isnan(Z).all(axis=0))
True [False False True]
61. Find the nearest value from a given value in an array (★★☆)¶
In [61]:
Copied!
Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print(m)
Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print(m)
0.5530715877981844
62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)¶
In [62]:
Copied!
A = np.arange(3).reshape(3,1)
B = np.arange(3).reshape(1,3)
it = np.nditer([A,B,None])
for x,y,z in it: z[...] = x + y
print(it.operands[2])
A = np.arange(3).reshape(3,1)
B = np.arange(3).reshape(1,3)
it = np.nditer([A,B,None])
for x,y,z in it: z[...] = x + y
print(it.operands[2])
[[0 1 2] [1 2 3] [2 3 4]]
63. Create an array class that has a name attribute (★★☆)¶
In [63]:
Copied!
class NamedArray(np.ndarray):
def __new__(cls, array, name="no name"):
obj = np.asarray(array).view(cls)
obj.name = name
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.name = getattr(obj, 'name', "no name")
Z = NamedArray(np.arange(10), "range_10")
print (Z.name)
class NamedArray(np.ndarray):
def __new__(cls, array, name="no name"):
obj = np.asarray(array).view(cls)
obj.name = name
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.name = getattr(obj, 'name', "no name")
Z = NamedArray(np.arange(10), "range_10")
print (Z.name)
range_10
64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)¶
In [64]:
Copied!
# Author: Brett Olsen
Z = np.ones(10)
I = np.random.randint(0,len(Z),20)
Z += np.bincount(I, minlength=len(Z))
print(Z)
# Another solution
# Author: Bartosz Telenczuk
np.add.at(Z, I, 1)
print(Z)
# Author: Brett Olsen
Z = np.ones(10)
I = np.random.randint(0,len(Z),20)
Z += np.bincount(I, minlength=len(Z))
print(Z)
# Another solution
# Author: Bartosz Telenczuk
np.add.at(Z, I, 1)
print(Z)
[3. 1. 5. 3. 2. 3. 4. 2. 3. 4.] [5. 1. 9. 5. 3. 5. 7. 3. 5. 7.]
65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)¶
In [65]:
Copied!
# Author: Alan G Isaac
X = [1,2,3,4,5,6]
I = [1,3,9,3,4,1]
F = np.bincount(I,X)
print(F)
# Author: Alan G Isaac
X = [1,2,3,4,5,6]
I = [1,3,9,3,4,1]
F = np.bincount(I,X)
print(F)
[0. 7. 0. 6. 5. 0. 0. 0. 0. 3.]
66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆)¶
In [66]:
Copied!
# Author: Fisher Wang
w, h = 256, 256
I = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte)
colors = np.unique(I.reshape(-1, 3), axis=0)
n = len(colors)
print(n)
# Faster version
# Author: Mark Setchell
# https://stackoverflow.com/a/59671950/2836621
w, h = 256, 256
I = np.random.randint(0,4,(h,w,3), dtype=np.uint8)
# View each pixel as a single 24-bit integer, rather than three 8-bit bytes
I24 = np.dot(I.astype(np.uint32),[1,256,65536])
# Count unique colours
n = len(np.unique(I24))
print(n)
# Author: Fisher Wang
w, h = 256, 256
I = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte)
colors = np.unique(I.reshape(-1, 3), axis=0)
n = len(colors)
print(n)
# Faster version
# Author: Mark Setchell
# https://stackoverflow.com/a/59671950/2836621
w, h = 256, 256
I = np.random.randint(0,4,(h,w,3), dtype=np.uint8)
# View each pixel as a single 24-bit integer, rather than three 8-bit bytes
I24 = np.dot(I.astype(np.uint32),[1,256,65536])
# Count unique colours
n = len(np.unique(I24))
print(n)
64 64
67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)¶
In [67]:
Copied!
A = np.random.randint(0,10,(3,4,3,4))
# solution by passing a tuple of axes (introduced in numpy 1.7.0)
sum = A.sum(axis=(-2,-1))
print(sum)
# solution by flattening the last two dimensions into one
# (useful for functions that don't accept tuples for axis argument)
sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
print(sum)
A = np.random.randint(0,10,(3,4,3,4))
# solution by passing a tuple of axes (introduced in numpy 1.7.0)
sum = A.sum(axis=(-2,-1))
print(sum)
# solution by flattening the last two dimensions into one
# (useful for functions that don't accept tuples for axis argument)
sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
print(sum)
[[72 37 48 52] [41 58 66 31] [55 54 42 53]] [[72 37 48 52] [41 58 66 31] [55 54 42 53]]
68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★)¶
In [68]:
Copied!
# Author: Jaime Fernández del RÃo
D = np.random.uniform(0,1,100)
S = np.random.randint(0,10,100)
D_sums = np.bincount(S, weights=D)
D_counts = np.bincount(S)
D_means = D_sums / D_counts
print(D_means)
# Pandas solution as a reference due to more intuitive code
import pandas as pd
print(pd.Series(D).groupby(S).mean())
# Author: Jaime Fernández del RÃo
D = np.random.uniform(0,1,100)
S = np.random.randint(0,10,100)
D_sums = np.bincount(S, weights=D)
D_counts = np.bincount(S)
D_means = D_sums / D_counts
print(D_means)
# Pandas solution as a reference due to more intuitive code
import pandas as pd
print(pd.Series(D).groupby(S).mean())
[0.33893787 0.33333011 0.45981486 0.42545144 0.48552272 0.65054824 0.41261355 0.40259611 0.61996853 0.51723681] 0 0.338938 1 0.333330 2 0.459815 3 0.425451 4 0.485523 5 0.650548 6 0.412614 7 0.402596 8 0.619969 9 0.517237 dtype: float64
69. How to get the diagonal of a dot product? (★★★)¶
In [69]:
Copied!
# Author: Mathieu Blondel
A = np.random.uniform(0,1,(5,5))
B = np.random.uniform(0,1,(5,5))
# Slow version
np.diag(np.dot(A, B))
# Fast version
np.sum(A * B.T, axis=1)
# Faster version
np.einsum("ij,ji->i", A, B)
# Author: Mathieu Blondel
A = np.random.uniform(0,1,(5,5))
B = np.random.uniform(0,1,(5,5))
# Slow version
np.diag(np.dot(A, B))
# Fast version
np.sum(A * B.T, axis=1)
# Faster version
np.einsum("ij,ji->i", A, B)
Out[69]:
array([2.14590355, 1.16320916, 2.23232537, 1.82047492, 1.8787372 ])
70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)¶
In [70]:
Copied!
# Author: Warren Weckesser
Z = np.array([1,2,3,4,5])
nz = 3
Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
Z0[::nz+1] = Z
print(Z0)
# Author: Warren Weckesser
Z = np.array([1,2,3,4,5])
nz = 3
Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
Z0[::nz+1] = Z
print(Z0)
[1. 0. 0. 0. 2. 0. 0. 0. 3. 0. 0. 0. 4. 0. 0. 0. 5.]
71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)¶
In [71]:
Copied!
A = np.ones((5,5,3))
B = 2*np.ones((5,5))
print(A * B[:,:,None])
A = np.ones((5,5,3))
B = 2*np.ones((5,5))
print(A * B[:,:,None])
[[[2. 2. 2.] [2. 2. 2.] [2. 2. 2.] [2. 2. 2.] [2. 2. 2.]] [[2. 2. 2.] [2. 2. 2.] [2. 2. 2.] [2. 2. 2.] [2. 2. 2.]] [[2. 2. 2.] [2. 2. 2.] [2. 2. 2.] [2. 2. 2.] [2. 2. 2.]] [[2. 2. 2.] [2. 2. 2.] [2. 2. 2.] [2. 2. 2.] [2. 2. 2.]] [[2. 2. 2.] [2. 2. 2.] [2. 2. 2.] [2. 2. 2.] [2. 2. 2.]]]
72. How to swap two rows of an array? (★★★)¶
In [72]:
Copied!
# Author: Eelco Hoogendoorn
A = np.arange(25).reshape(5,5)
A[[0,1]] = A[[1,0]]
print(A)
# Author: Eelco Hoogendoorn
A = np.arange(25).reshape(5,5)
A[[0,1]] = A[[1,0]]
print(A)
[[ 5 6 7 8 9] [ 0 1 2 3 4] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]]
73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)¶
In [73]:
Copied!
# Author: Nicolas P. Rougier
faces = np.random.randint(0,100,(10,3))
F = np.roll(faces.repeat(2,axis=1),-1,axis=1)
F = F.reshape(len(F)*3,2)
F = np.sort(F,axis=1)
G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )
G = np.unique(G)
print(G)
# Author: Nicolas P. Rougier
faces = np.random.randint(0,100,(10,3))
F = np.roll(faces.repeat(2,axis=1),-1,axis=1)
F = F.reshape(len(F)*3,2)
F = np.sort(F,axis=1)
G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )
G = np.unique(G)
print(G)
[( 2, 52) ( 2, 58) ( 2, 61) ( 2, 66) ( 3, 91) ( 3, 92) ( 5, 61) ( 5, 74) ( 8, 15) ( 8, 79) ( 9, 41) ( 9, 50) (15, 79) (20, 57) (20, 96) (41, 50) (52, 61) (57, 96) (58, 66) (61, 74) (71, 72) (71, 79) (72, 79) (75, 81) (75, 89) (81, 89) (86, 96) (86, 98) (91, 92) (96, 98)]
74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)¶
In [74]:
Copied!
# Author: Jaime Fernández del Río
C = np.bincount([1,1,2,3,4,4,6])
A = np.repeat(np.arange(len(C)), C)
print(A)
# Author: Jaime Fernández del Río
C = np.bincount([1,1,2,3,4,4,6])
A = np.repeat(np.arange(len(C)), C)
print(A)
[1 1 2 3 4 4 6]
75. How to compute averages using a sliding window over an array? (★★★)¶
In [75]:
Copied!
# Author: Jaime Fernandez del Rio
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
Z = np.arange(20)
print(moving_average(Z, n=3))
# Author: Jeff Luo (@Jeff1999)
# make sure your NumPy >= 1.20.0
from numpy.lib.stride_tricks import sliding_window_view
Z = np.arange(20)
print(sliding_window_view(Z, window_shape=3).mean(axis=-1))
# Author: Jaime Fernandez del Rio
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
Z = np.arange(20)
print(moving_average(Z, n=3))
# Author: Jeff Luo (@Jeff1999)
# make sure your NumPy >= 1.20.0
from numpy.lib.stride_tricks import sliding_window_view
Z = np.arange(20)
print(sliding_window_view(Z, window_shape=3).mean(axis=-1))
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18.] [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18.]
76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (★★★)¶
In [76]:
Copied!
# Author: Joe Kington / Erik Rigtorp
from numpy.lib import stride_tricks
def rolling(a, window):
shape = (a.size - window + 1, window)
strides = (a.strides[0], a.strides[0])
return stride_tricks.as_strided(a, shape=shape, strides=strides)
Z = rolling(np.arange(10), 3)
print(Z)
# Author: Jeff Luo (@Jeff1999)
Z = np.arange(10)
print(sliding_window_view(Z, window_shape=3))
# Author: Joe Kington / Erik Rigtorp
from numpy.lib import stride_tricks
def rolling(a, window):
shape = (a.size - window + 1, window)
strides = (a.strides[0], a.strides[0])
return stride_tricks.as_strided(a, shape=shape, strides=strides)
Z = rolling(np.arange(10), 3)
print(Z)
# Author: Jeff Luo (@Jeff1999)
Z = np.arange(10)
print(sliding_window_view(Z, window_shape=3))
[[0 1 2] [1 2 3] [2 3 4] [3 4 5] [4 5 6] [5 6 7] [6 7 8] [7 8 9]] [[0 1 2] [1 2 3] [2 3 4] [3 4 5] [4 5 6] [5 6 7] [6 7 8] [7 8 9]]
77. How to negate a boolean, or to change the sign of a float inplace? (★★★)¶
In [77]:
Copied!
# Author: Nathaniel J. Smith
Z = np.random.randint(0,2,100)
np.logical_not(Z, out=Z)
Z = np.random.uniform(-1.0,1.0,100)
np.negative(Z, out=Z)
# Author: Nathaniel J. Smith
Z = np.random.randint(0,2,100)
np.logical_not(Z, out=Z)
Z = np.random.uniform(-1.0,1.0,100)
np.negative(Z, out=Z)
Out[77]:
array([ 0.24755614, -0.8547294 , -0.0347516 , 0.50842836, 0.5683712 ,
-0.76708245, 0.33536143, 0.89106461, 0.35976065, -0.2524336 ,
-0.18813014, -0.83654191, -0.06043748, 0.56578852, -0.0735836 ,
0.1481124 , 0.57940707, -0.14290676, -0.35233885, -0.70084748,
0.01775214, 0.85838832, 0.15350084, -0.7548454 , -0.80743527,
0.56158562, 0.55225073, 0.57038592, 0.0059291 , 0.33561025,
0.89818957, -0.5464155 , 0.4394059 , 0.90420728, 0.46176908,
-0.10753203, -0.16721395, 0.06604806, 0.90905807, -0.7941227 ,
-0.51003923, -0.02967532, 0.2198734 , -0.3060711 , 0.8130367 ,
0.087638 , -0.73049841, 0.46107188, -0.511218 , -0.02559935,
0.36536236, -0.50348855, -0.33405233, 0.1982736 , 0.13956211,
-0.2765044 , -0.83496803, -0.58638013, -0.74047844, -0.28133266,
0.66526159, -0.586181 , 0.37830591, -0.55148882, -0.06274637,
-0.82175924, 0.86603033, -0.04106241, 0.92804419, -0.02596698,
-0.27611661, -0.67595076, -0.8965136 , -0.38492086, 0.08966282,
0.05057763, -0.92900028, -0.31129895, -0.74933168, 0.96935517,
-0.96953747, 0.37730834, 0.9669432 , -0.78933731, 0.10176542,
0.51179952, 0.58765906, 0.98387638, -0.29541974, 0.2294312 ,
0.78495699, 0.35960645, 0.35098225, 0.64941684, 0.68689366,
0.60547832, -0.68645225, -0.88637139, 0.09510804, 0.99011567])
78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])? (★★★)¶
In [78]:
Copied!
def distance(P0, P1, p):
T = P1 - P0
L = (T**2).sum(axis=1)
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
U = U.reshape(len(U),1)
D = P0 + U*T - p
return np.sqrt((D**2).sum(axis=1))
P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10,10,( 1,2))
print(distance(P0, P1, p))
def distance(P0, P1, p):
T = P1 - P0
L = (T**2).sum(axis=1)
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
U = U.reshape(len(U),1)
D = P0 + U*T - p
return np.sqrt((D**2).sum(axis=1))
P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10,10,( 1,2))
print(distance(P0, P1, p))
[ 5.81471492 3.20462521 6.05169356 7.49270773 3.02091091 1.25521578 3.83096767 11.39229698 0.20498379 8.03234065]
79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (★★★)¶
In [79]:
Copied!
# Author: Italmassov Kuanysh
# based on distance function from previous question
P0 = np.random.uniform(-10, 10, (10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10, 10, (10,2))
print(np.array([distance(P0,P1,p_i) for p_i in p]))
# Author: Italmassov Kuanysh
# based on distance function from previous question
P0 = np.random.uniform(-10, 10, (10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10, 10, (10,2))
print(np.array([distance(P0,P1,p_i) for p_i in p]))
[[ 9.77401102 17.7545296 14.64342675 1.88287164 10.42452814 4.53003461 5.31396446 12.26914191 7.42459146 9.97461428] [ 8.58953774 15.58482363 12.77274557 2.33698799 8.12562118 2.49339023 3.20781268 10.27240853 5.1447985 10.20878328] [ 0.9540553 4.43283251 1.65219109 0.71610932 1.5190058 3.95792916 3.86398111 0.96103422 4.01780947 6.12606013] [ 5.40624219 5.38310024 5.01651701 8.1919011 4.18290997 9.85614852 9.28679907 1.55409157 7.33884715 14.95987745] [ 5.1762762 14.93277997 10.87856891 2.29284751 9.35592621 5.4351483 5.89580256 8.81369298 6.7203924 5.60209631] [ 2.71597771 6.51756878 4.55272388 2.79484052 0.90117661 4.94418275 4.59058684 1.66860929 3.6995443 9.77443225] [ 9.09443705 3.45716747 2.50353338 12.3723253 2.22786257 3.96950766 3.45270484 3.99558156 0.58257292 5.40697859] [ 3.30195432 4.30846692 0.55161882 4.24458987 0.2180451 1.42438395 1.50809183 1.71583288 2.46253512 2.65152938] [ 8.73599982 13.18410905 11.33769467 5.11097684 4.66635695 1.45376931 0.70526909 8.47229946 1.5448634 12.6968735 ] [ 3.27231269 5.35216098 1.21615249 5.30508504 1.22720793 0.1831468 0.09173181 0.90704007 0.96649 1.71260265]]
80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a fill value when necessary) (★★★)¶
In [80]:
Copied!
# Author: Nicolas Rougier
Z = np.random.randint(0,10,(10,10))
shape = (5,5)
fill = 0
position = (1,1)
R = np.ones(shape, dtype=Z.dtype)*fill
P = np.array(list(position)).astype(int)
Rs = np.array(list(R.shape)).astype(int)
Zs = np.array(list(Z.shape)).astype(int)
R_start = np.zeros((len(shape),)).astype(int)
R_stop = np.array(list(shape)).astype(int)
Z_start = (P-Rs//2)
Z_stop = (P+Rs//2)+Rs%2
R_start = (R_start - np.minimum(Z_start,0)).tolist()
Z_start = (np.maximum(Z_start,0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
R[r] = Z[z]
print(Z)
print(R)
# Author: Nicolas Rougier
Z = np.random.randint(0,10,(10,10))
shape = (5,5)
fill = 0
position = (1,1)
R = np.ones(shape, dtype=Z.dtype)*fill
P = np.array(list(position)).astype(int)
Rs = np.array(list(R.shape)).astype(int)
Zs = np.array(list(Z.shape)).astype(int)
R_start = np.zeros((len(shape),)).astype(int)
R_stop = np.array(list(shape)).astype(int)
Z_start = (P-Rs//2)
Z_stop = (P+Rs//2)+Rs%2
R_start = (R_start - np.minimum(Z_start,0)).tolist()
Z_start = (np.maximum(Z_start,0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
R[r] = Z[z]
print(Z)
print(R)
[[9 9 1 9 3 1 9 8 4 6] [7 5 8 3 8 9 8 5 9 0] [5 8 7 1 8 8 7 7 5 1] [4 9 5 8 8 8 8 0 6 5] [7 5 8 0 0 0 3 1 2 7] [1 0 3 8 4 2 7 9 1 6] [2 0 5 0 7 6 8 7 0 2] [5 0 9 5 4 8 1 5 3 1] [7 2 2 1 0 3 9 4 7 9] [9 2 8 4 8 3 5 3 6 9]] [[0 0 0 0 0] [0 9 9 1 9] [0 7 5 8 3] [0 5 8 7 1] [0 4 9 5 8]]
C:\Users\franc\AppData\Local\Temp\ipykernel_22896\533828575.py:25: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. R[r] = Z[z]
81. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]? (★★★)¶
In [81]:
Copied!
# Author: Stefan van der Walt
Z = np.arange(1,15,dtype=np.uint32)
R = stride_tricks.as_strided(Z,(11,4),(4,4))
print(R)
# Author: Jeff Luo (@Jeff1999)
Z = np.arange(1, 15, dtype=np.uint32)
print(sliding_window_view(Z, window_shape=4))
# Author: Stefan van der Walt
Z = np.arange(1,15,dtype=np.uint32)
R = stride_tricks.as_strided(Z,(11,4),(4,4))
print(R)
# Author: Jeff Luo (@Jeff1999)
Z = np.arange(1, 15, dtype=np.uint32)
print(sliding_window_view(Z, window_shape=4))
[[ 1 2 3 4] [ 2 3 4 5] [ 3 4 5 6] [ 4 5 6 7] [ 5 6 7 8] [ 6 7 8 9] [ 7 8 9 10] [ 8 9 10 11] [ 9 10 11 12] [10 11 12 13] [11 12 13 14]] [[ 1 2 3 4] [ 2 3 4 5] [ 3 4 5 6] [ 4 5 6 7] [ 5 6 7 8] [ 6 7 8 9] [ 7 8 9 10] [ 8 9 10 11] [ 9 10 11 12] [10 11 12 13] [11 12 13 14]]
82. Compute a matrix rank (★★★)¶
In [82]:
Copied!
# Author: Stefan van der Walt
Z = np.random.uniform(0,1,(10,10))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
print(rank)
# alternative solution:
# Author: Jeff Luo (@Jeff1999)
rank = np.linalg.matrix_rank(Z)
print(rank)
# Author: Stefan van der Walt
Z = np.random.uniform(0,1,(10,10))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
print(rank)
# alternative solution:
# Author: Jeff Luo (@Jeff1999)
rank = np.linalg.matrix_rank(Z)
print(rank)
10 10
83. How to find the most frequent value in an array?¶
In [83]:
Copied!
Z = np.random.randint(0,10,50)
print(np.bincount(Z).argmax())
Z = np.random.randint(0,10,50)
print(np.bincount(Z).argmax())
9
84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)¶
In [84]:
Copied!
# Author: Chris Barker
Z = np.random.randint(0,5,(10,10))
n = 3
i = 1 + (Z.shape[0]-3)
j = 1 + (Z.shape[1]-3)
C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)
print(C)
# Author: Jeff Luo (@Jeff1999)
Z = np.random.randint(0,5,(10,10))
print(sliding_window_view(Z, window_shape=(3, 3)))
# Author: Chris Barker
Z = np.random.randint(0,5,(10,10))
n = 3
i = 1 + (Z.shape[0]-3)
j = 1 + (Z.shape[1]-3)
C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)
print(C)
# Author: Jeff Luo (@Jeff1999)
Z = np.random.randint(0,5,(10,10))
print(sliding_window_view(Z, window_shape=(3, 3)))
[[[[0 0 2] [3 0 1] [0 4 2]] [[0 2 0] [0 1 2] [4 2 1]] [[2 0 1] [1 2 0] [2 1 0]] [[0 1 2] [2 0 1] [1 0 4]] [[1 2 4] [0 1 3] [0 4 2]] [[2 4 2] [1 3 0] [4 2 2]] [[4 2 0] [3 0 4] [2 2 2]] [[2 0 4] [0 4 0] [2 2 4]]] [[[3 0 1] [0 4 2] [4 3 1]] [[0 1 2] [4 2 1] [3 1 2]] [[1 2 0] [2 1 0] [1 2 0]] [[2 0 1] [1 0 4] [2 0 0]] [[0 1 3] [0 4 2] [0 0 2]] [[1 3 0] [4 2 2] [0 2 3]] [[3 0 4] [2 2 2] [2 3 1]] [[0 4 0] [2 2 4] [3 1 2]]] [[[0 4 2] [4 3 1] [2 1 1]] [[4 2 1] [3 1 2] [1 1 0]] [[2 1 0] [1 2 0] [1 0 0]] [[1 0 4] [2 0 0] [0 0 2]] [[0 4 2] [0 0 2] [0 2 3]] [[4 2 2] [0 2 3] [2 3 1]] [[2 2 2] [2 3 1] [3 1 2]] [[2 2 4] [3 1 2] [1 2 2]]] [[[4 3 1] [2 1 1] [2 2 3]] [[3 1 2] [1 1 0] [2 3 3]] [[1 2 0] [1 0 0] [3 3 0]] [[2 0 0] [0 0 2] [3 0 3]] [[0 0 2] [0 2 3] [0 3 1]] [[0 2 3] [2 3 1] [3 1 2]] [[2 3 1] [3 1 2] [1 2 1]] [[3 1 2] [1 2 2] [2 1 3]]] [[[2 1 1] [2 2 3] [2 1 3]] [[1 1 0] [2 3 3] [1 3 2]] [[1 0 0] [3 3 0] [3 2 3]] [[0 0 2] [3 0 3] [2 3 2]] [[0 2 3] [0 3 1] [3 2 2]] [[2 3 1] [3 1 2] [2 2 0]] [[3 1 2] [1 2 1] [2 0 2]] [[1 2 2] [2 1 3] [0 2 1]]] [[[2 2 3] [2 1 3] [0 2 3]] [[2 3 3] [1 3 2] [2 3 1]] [[3 3 0] [3 2 3] [3 1 4]] [[3 0 3] [2 3 2] [1 4 0]] [[0 3 1] [3 2 2] [4 0 3]] [[3 1 2] [2 2 0] [0 3 3]] [[1 2 1] [2 0 2] [3 3 4]] [[2 1 3] [0 2 1] [3 4 4]]] [[[2 1 3] [0 2 3] [1 0 4]] [[1 3 2] [2 3 1] [0 4 2]] [[3 2 3] [3 1 4] [4 2 0]] [[2 3 2] [1 4 0] [2 0 1]] [[3 2 2] [4 0 3] [0 1 3]] [[2 2 0] [0 3 3] [1 3 4]] [[2 0 2] [3 3 4] [3 4 1]] [[0 2 1] [3 4 4] [4 1 3]]] [[[0 2 3] [1 0 4] [0 4 2]] [[2 3 1] [0 4 2] [4 2 2]] [[3 1 4] [4 2 0] [2 2 0]] [[1 4 0] [2 0 1] [2 0 1]] [[4 0 3] [0 1 3] [0 1 3]] [[0 3 3] [1 3 4] [1 3 1]] [[3 3 4] [3 4 1] [3 1 0]] [[3 4 4] [4 1 3] [1 0 4]]]] [[[[4 2 0] [0 2 0] [3 2 4]] [[2 0 2] [2 0 2] [2 4 3]] [[0 2 1] [0 2 2] [4 3 0]] [[2 1 4] [2 2 4] [3 0 2]] [[1 4 4] [2 4 1] [0 2 3]] [[4 4 0] [4 1 3] [2 3 3]] [[4 0 1] [1 3 4] [3 3 2]] [[0 1 2] [3 4 3] [3 2 3]]] [[[0 2 0] [3 2 4] [1 3 2]] [[2 0 2] [2 4 3] [3 2 4]] [[0 2 2] [4 3 0] [2 4 2]] [[2 2 4] [3 0 2] [4 2 1]] [[2 4 1] [0 2 3] [2 1 3]] [[4 1 3] [2 3 3] [1 3 0]] [[1 3 4] [3 3 2] [3 0 1]] [[3 4 3] [3 2 3] [0 1 4]]] [[[3 2 4] [1 3 2] [2 1 3]] [[2 4 3] [3 2 4] [1 3 3]] [[4 3 0] [2 4 2] [3 3 0]] [[3 0 2] [4 2 1] [3 0 4]] [[0 2 3] [2 1 3] [0 4 0]] [[2 3 3] [1 3 0] [4 0 1]] [[3 3 2] [3 0 1] [0 1 1]] [[3 2 3] [0 1 4] [1 1 0]]] [[[1 3 2] [2 1 3] [1 0 1]] [[3 2 4] [1 3 3] [0 1 2]] [[2 4 2] [3 3 0] [1 2 4]] [[4 2 1] [3 0 4] [2 4 3]] [[2 1 3] [0 4 0] [4 3 2]] [[1 3 0] [4 0 1] [3 2 4]] [[3 0 1] [0 1 1] [2 4 0]] [[0 1 4] [1 1 0] [4 0 3]]] [[[2 1 3] [1 0 1] [1 2 0]] [[1 3 3] [0 1 2] [2 0 0]] [[3 3 0] [1 2 4] [0 0 1]] [[3 0 4] [2 4 3] [0 1 2]] [[0 4 0] [4 3 2] [1 2 0]] [[4 0 1] [3 2 4] [2 0 1]] [[0 1 1] [2 4 0] [0 1 0]] [[1 1 0] [4 0 3] [1 0 0]]] [[[1 0 1] [1 2 0] [4 3 2]] [[0 1 2] [2 0 0] [3 2 1]] [[1 2 4] [0 0 1] [2 1 0]] [[2 4 3] [0 1 2] [1 0 2]] [[4 3 2] [1 2 0] [0 2 4]] [[3 2 4] [2 0 1] [2 4 1]] [[2 4 0] [0 1 0] [4 1 4]] [[4 0 3] [1 0 0] [1 4 2]]] [[[1 2 0] [4 3 2] [3 0 1]] [[2 0 0] [3 2 1] [0 1 2]] [[0 0 1] [2 1 0] [1 2 3]] [[0 1 2] [1 0 2] [2 3 4]] [[1 2 0] [0 2 4] [3 4 1]] [[2 0 1] [2 4 1] [4 1 4]] [[0 1 0] [4 1 4] [1 4 4]] [[1 0 0] [1 4 2] [4 4 1]]] [[[4 3 2] [3 0 1] [2 2 0]] [[3 2 1] [0 1 2] [2 0 4]] [[2 1 0] [1 2 3] [0 4 4]] [[1 0 2] [2 3 4] [4 4 3]] [[0 2 4] [3 4 1] [4 3 0]] [[2 4 1] [4 1 4] [3 0 3]] [[4 1 4] [1 4 4] [0 3 3]] [[1 4 2] [4 4 1] [3 3 0]]]]
85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)¶
In [85]:
Copied!
# Author: Eric O. Lebigot
# Note: only works for 2d array and value setting using indices
class Symetric(np.ndarray):
def __setitem__(self, index, value):
i,j = index
super(Symetric, self).__setitem__((i,j), value)
super(Symetric, self).__setitem__((j,i), value)
def symetric(Z):
return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)
S = symetric(np.random.randint(0,10,(5,5)))
S[2,3] = 42
print(S)
# Author: Eric O. Lebigot
# Note: only works for 2d array and value setting using indices
class Symetric(np.ndarray):
def __setitem__(self, index, value):
i,j = index
super(Symetric, self).__setitem__((i,j), value)
super(Symetric, self).__setitem__((j,i), value)
def symetric(Z):
return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)
S = symetric(np.random.randint(0,10,(5,5)))
S[2,3] = 42
print(S)
[[ 2 11 9 9 17] [11 7 8 11 1] [ 9 8 9 42 13] [ 9 11 42 6 8] [17 1 13 8 4]]
86. Consider a set of p matrices with shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★)¶
In [86]:
Copied!
# Author: Stefan van der Walt
p, n = 10, 20
M = np.ones((p,n,n))
V = np.ones((p,n,1))
S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
print(S)
# It works, because:
# M is (p,n,n)
# V is (p,n,1)
# Thus, summing over the paired axes 0 and 0 (of M and V independently),
# and 2 and 1, to remain with a (n,1) vector.
# Author: Stefan van der Walt
p, n = 10, 20
M = np.ones((p,n,n))
V = np.ones((p,n,1))
S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
print(S)
# It works, because:
# M is (p,n,n)
# V is (p,n,1)
# Thus, summing over the paired axes 0 and 0 (of M and V independently),
# and 2 and 1, to remain with a (n,1) vector.
[[200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.] [200.]]
87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)¶
In [87]:
Copied!
# Author: Robert Kern
Z = np.ones((16,16))
k = 4
S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
np.arange(0, Z.shape[1], k), axis=1)
print(S)
# alternative solution:
# Author: Sebastian Wallkötter (@FirefoxMetzger)
Z = np.ones((16,16))
k = 4
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
# Author: Jeff Luo (@Jeff1999)
Z = np.ones((16, 16))
k = 4
print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1)))
# Author: Robert Kern
Z = np.ones((16,16))
k = 4
S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
np.arange(0, Z.shape[1], k), axis=1)
print(S)
# alternative solution:
# Author: Sebastian Wallkötter (@FirefoxMetzger)
Z = np.ones((16,16))
k = 4
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
# Author: Jeff Luo (@Jeff1999)
Z = np.ones((16, 16))
k = 4
print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1)))
[[16. 16. 16. 16.] [16. 16. 16. 16.] [16. 16. 16. 16.] [16. 16. 16. 16.]] [[16. 16. 16. 16.] [16. 16. 16. 16.] [16. 16. 16. 16.] [16. 16. 16. 16.]]
88. How to implement the Game of Life using numpy arrays? (★★★)¶
In [88]:
Copied!
# Author: Nicolas Rougier
def iterate(Z):
# Count neighbours
N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +
Z[1:-1,0:-2] + Z[1:-1,2:] +
Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:])
# Apply rules
birth = (N==3) & (Z[1:-1,1:-1]==0)
survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)
Z[...] = 0
Z[1:-1,1:-1][birth | survive] = 1
return Z
Z = np.random.randint(0,2,(50,50))
for i in range(100): Z = iterate(Z)
print(Z)
# Author: Nicolas Rougier
def iterate(Z):
# Count neighbours
N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +
Z[1:-1,0:-2] + Z[1:-1,2:] +
Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:])
# Apply rules
birth = (N==3) & (Z[1:-1,1:-1]==0)
survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)
Z[...] = 0
Z[1:-1,1:-1][birth | survive] = 1
return Z
Z = np.random.randint(0,2,(50,50))
for i in range(100): Z = iterate(Z)
print(Z)
[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]
89. How to get the n largest values of an array (★★★)¶
In [89]:
Copied!
Z = np.arange(10000)
np.random.shuffle(Z)
n = 5
# Slow
print (Z[np.argsort(Z)[-n:]])
# Fast
print (Z[np.argpartition(-Z,n)[:n]])
Z = np.arange(10000)
np.random.shuffle(Z)
n = 5
# Slow
print (Z[np.argsort(Z)[-n:]])
# Fast
print (Z[np.argpartition(-Z,n)[:n]])
[9995 9996 9997 9998 9999] [9999 9998 9997 9996 9995]
90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)¶
In [90]:
Copied!
# Author: Stefan Van der Walt
def cartesian(arrays):
arrays = [np.asarray(a) for a in arrays]
shape = (len(x) for x in arrays)
ix = np.indices(shape, dtype=int)
ix = ix.reshape(len(arrays), -1).T
for n, arr in enumerate(arrays):
ix[:, n] = arrays[n][ix[:, n]]
return ix
print (cartesian(([1, 2, 3], [4, 5], [6, 7])))
# Author: Stefan Van der Walt
def cartesian(arrays):
arrays = [np.asarray(a) for a in arrays]
shape = (len(x) for x in arrays)
ix = np.indices(shape, dtype=int)
ix = ix.reshape(len(arrays), -1).T
for n, arr in enumerate(arrays):
ix[:, n] = arrays[n][ix[:, n]]
return ix
print (cartesian(([1, 2, 3], [4, 5], [6, 7])))
[[1 4 6] [1 4 7] [1 5 6] [1 5 7] [2 4 6] [2 4 7] [2 5 6] [2 5 7] [3 4 6] [3 4 7] [3 5 6] [3 5 7]]
91. How to create a record array from a regular array? (★★★)¶
In [91]:
Copied!
Z = np.array([("Hello", 2.5, 3),
("World", 3.6, 2)])
R = np.core.records.fromarrays(Z.T,
names='col1, col2, col3',
formats = 'S8, f8, i8')
print(R)
Z = np.array([("Hello", 2.5, 3),
("World", 3.6, 2)])
R = np.core.records.fromarrays(Z.T,
names='col1, col2, col3',
formats = 'S8, f8, i8')
print(R)
[(b'Hello', 2.5, 3) (b'World', 3.6, 2)]
92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)¶
In [92]:
Copied!
# Author: Ryan G.
x = np.random.rand(int(5e7))
%timeit np.power(x,3)
%timeit x*x*x
%timeit np.einsum('i,i,i->i',x,x,x)
# Author: Ryan G.
x = np.random.rand(int(5e7))
%timeit np.power(x,3)
%timeit x*x*x
%timeit np.einsum('i,i,i->i',x,x,x)
972 ms ± 19.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 261 ms ± 65.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 129 ms ± 6.84 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (★★★)¶
In [93]:
Copied!
# Author: Gabe Schwartz
A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))
C = (A[..., np.newaxis, np.newaxis] == B)
rows = np.where(C.any((3,1)).all(1))[0]
print(rows)
# Author: Gabe Schwartz
A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))
C = (A[..., np.newaxis, np.newaxis] == B)
rows = np.where(C.any((3,1)).all(1))[0]
print(rows)
[0 1 3 4 5 7]
94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)¶
In [94]:
Copied!
# Author: Robert Kern
Z = np.random.randint(0,5,(10,3))
print(Z)
# solution for arrays of all dtypes (including string arrays and record arrays)
E = np.all(Z[:,1:] == Z[:,:-1], axis=1)
U = Z[~E]
print(U)
# soluiton for numerical arrays only, will work for any number of columns in Z
U = Z[Z.max(axis=1) != Z.min(axis=1),:]
print(U)
# Author: Robert Kern
Z = np.random.randint(0,5,(10,3))
print(Z)
# solution for arrays of all dtypes (including string arrays and record arrays)
E = np.all(Z[:,1:] == Z[:,:-1], axis=1)
U = Z[~E]
print(U)
# soluiton for numerical arrays only, will work for any number of columns in Z
U = Z[Z.max(axis=1) != Z.min(axis=1),:]
print(U)
[[4 3 4] [4 2 2] [1 1 2] [0 0 1] [4 3 4] [4 1 2] [2 4 2] [1 0 1] [0 3 2] [1 3 4]] [[4 3 4] [4 2 2] [1 1 2] [0 0 1] [4 3 4] [4 1 2] [2 4 2] [1 0 1] [0 3 2] [1 3 4]] [[4 3 4] [4 2 2] [1 1 2] [0 0 1] [4 3 4] [4 1 2] [2 4 2] [1 0 1] [0 3 2] [1 3 4]]
95. Convert a vector of ints into a matrix binary representation (★★★)¶
In [95]:
Copied!
# Author: Warren Weckesser
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])
B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])
# Author: Daniel T. McDonald
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))
# Author: Warren Weckesser
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])
B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])
# Author: Daniel T. McDonald
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))
[[0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 1] [0 0 0 0 0 0 1 0] [0 0 0 0 0 0 1 1] [0 0 0 0 1 1 1 1] [0 0 0 1 0 0 0 0] [0 0 1 0 0 0 0 0] [0 1 0 0 0 0 0 0] [1 0 0 0 0 0 0 0]] [[0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 1] [0 0 0 0 0 0 1 0] [0 0 0 0 0 0 1 1] [0 0 0 0 1 1 1 1] [0 0 0 1 0 0 0 0] [0 0 1 0 0 0 0 0] [0 1 0 0 0 0 0 0] [1 0 0 0 0 0 0 0]]
96. Given a two dimensional array, how to extract unique rows? (★★★)¶
In [96]:
Copied!
# Author: Jaime Fernández del RÃo
Z = np.random.randint(0,2,(6,3))
T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))
_, idx = np.unique(T, return_index=True)
uZ = Z[idx]
print(uZ)
# Author: Andreas Kouzelis
# NumPy >= 1.13
uZ = np.unique(Z, axis=0)
print(uZ)
# Author: Jaime Fernández del RÃo
Z = np.random.randint(0,2,(6,3))
T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))
_, idx = np.unique(T, return_index=True)
uZ = Z[idx]
print(uZ)
# Author: Andreas Kouzelis
# NumPy >= 1.13
uZ = np.unique(Z, axis=0)
print(uZ)
[[0 0 1] [0 1 0] [0 1 1] [1 0 1] [1 1 0] [1 1 1]] [[0 0 1] [0 1 0] [0 1 1] [1 0 1] [1 1 0] [1 1 1]]
97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)¶
In [97]:
Copied!
# Author: Alex Riley
# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/
A = np.random.uniform(0,1,10)
B = np.random.uniform(0,1,10)
np.einsum('i->', A) # np.sum(A)
np.einsum('i,i->i', A, B) # A * B
np.einsum('i,i', A, B) # np.inner(A, B)
np.einsum('i,j->ij', A, B) # np.outer(A, B)
# Author: Alex Riley
# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/
A = np.random.uniform(0,1,10)
B = np.random.uniform(0,1,10)
np.einsum('i->', A) # np.sum(A)
np.einsum('i,i->i', A, B) # A * B
np.einsum('i,i', A, B) # np.inner(A, B)
np.einsum('i,j->ij', A, B) # np.outer(A, B)
Out[97]:
array([[0.37735129, 0.1742095 , 0.13686708, 0.44212482, 0.56708083,
0.57852989, 0.31897851, 0.41150828, 0.26765923, 0.40815694],
[0.49498734, 0.22851783, 0.17953423, 0.57995348, 0.74386346,
0.75888165, 0.41841735, 0.53979248, 0.35109971, 0.5353964 ],
[0.43633924, 0.20144211, 0.15826229, 0.51123825, 0.65572752,
0.6689663 , 0.36884157, 0.47583569, 0.3095 , 0.47196047],
[0.26370103, 0.12174127, 0.0956456 , 0.30896614, 0.39628803,
0.40428887, 0.2229089 , 0.28757065, 0.1870459 , 0.28522867],
[0.18752144, 0.0865719 , 0.06801491, 0.21971009, 0.28180589,
0.2874954 , 0.1585136 , 0.20449546, 0.13301093, 0.20283005],
[0.29433943, 0.13588591, 0.10675829, 0.34486372, 0.4423312 ,
0.45126163, 0.24880782, 0.32098237, 0.20877805, 0.31836828],
[0.12406708, 0.0572773 , 0.04499971, 0.14536358, 0.18644712,
0.19021139, 0.10487504, 0.13529735, 0.08800208, 0.13419548],
[0.07584982, 0.03501713, 0.02751109, 0.08886969, 0.11398658,
0.1162879 , 0.06411655, 0.08271558, 0.05380108, 0.08204194],
[0.24824174, 0.11460427, 0.09003844, 0.29085321, 0.37305592,
0.38058771, 0.20984102, 0.27071202, 0.17608047, 0.26850733],
[0.1877388 , 0.08667224, 0.06809374, 0.21996475, 0.28213253,
0.28782863, 0.15869733, 0.20473249, 0.1331651 , 0.20306515]])
98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?¶
In [98]:
Copied!
# Author: Bas Swinckels
phi = np.arange(0, 10*np.pi, 0.1)
a = 1
x = a*phi*np.cos(phi)
y = a*phi*np.sin(phi)
dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths
r = np.zeros_like(x)
r[1:] = np.cumsum(dr) # integrate path
r_int = np.linspace(0, r.max(), 200) # regular spaced path
x_int = np.interp(r_int, r, x) # integrate path
y_int = np.interp(r_int, r, y)
# Author: Bas Swinckels
phi = np.arange(0, 10*np.pi, 0.1)
a = 1
x = a*phi*np.cos(phi)
y = a*phi*np.sin(phi)
dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths
r = np.zeros_like(x)
r[1:] = np.cumsum(dr) # integrate path
r_int = np.linspace(0, r.max(), 200) # regular spaced path
x_int = np.interp(r_int, r, x) # integrate path
y_int = np.interp(r_int, r, y)
99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (★★★)¶
In [99]:
Copied!
# Author: Evgeni Burovski
X = np.asarray([[1.0, 0.0, 3.0, 8.0],
[2.0, 0.0, 1.0, 1.0],
[1.5, 2.5, 1.0, 0.0]])
n = 4
M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)
M &= (X.sum(axis=-1) == n)
print(X[M])
# Author: Evgeni Burovski
X = np.asarray([[1.0, 0.0, 3.0, 8.0],
[2.0, 0.0, 1.0, 1.0],
[1.5, 2.5, 1.0, 0.0]])
n = 4
M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)
M &= (X.sum(axis=-1) == n)
print(X[M])
[[2. 0. 1. 1.]]
100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means). (★★★)¶
In [100]:
Copied!
# Author: Jessica B. Hamrick
X = np.random.randn(100) # random 1D array
N = 1000 # number of bootstrap samples
idx = np.random.randint(0, X.size, (N, X.size))
means = X[idx].mean(axis=1)
confint = np.percentile(means, [2.5, 97.5])
print(confint)
# Author: Jessica B. Hamrick
X = np.random.randn(100) # random 1D array
N = 1000 # number of bootstrap samples
idx = np.random.randint(0, X.size, (N, X.size))
means = X[idx].mean(axis=1)
confint = np.percentile(means, [2.5, 97.5])
print(confint)
[-0.2753387 0.09900811]