You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
29. How to round away from zero a float array ? (★☆☆)
# Author: Charles R HarrisZ=np.random.uniform(-10,+10,10)
print(np.copysign(np.ceil(np.abs(Z)), Z))
# More readable but less efficientprint(np.where(Z>0, np.ceil(Z), np.floor(Z)))
30. How to find common values between two arrays? (★☆☆)
31. How to ignore all numpy warnings (not recommended)? (★☆☆)
# Suicide mode ondefaults=np.seterr(all="ignore")
Z=np.ones(1) /0# Back to sanity_=np.seterr(**defaults)
# Equivalently with a context managerwithnp.errstate(all="ignore"):
np.arange(3) /0
32. Is the following expressions true? (★☆☆)
np.sqrt(-1) ==np.emath.sqrt(-1)
np.sqrt(-1) ==np.emath.sqrt(-1)
33. How to get the dates of yesterday, today and tomorrow? (★☆☆)
42. Consider two random array A and B, check if they are 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 valuesequal=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)
43. Make an array immutable (read-only) (★★☆)
Z=np.zeros(10)
Z.flags.writeable=FalseZ[0] =1
44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)
# Author: Brett OlsenZ=np.ones(10)
I=np.random.randint(0,len(Z),20)
Z+=np.bincount(I, minlength=len(Z))
print(Z)
# Another solution# Author: Bartosz Telenczuknp.add.at(Z, I, 1)
print(Z)
65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)
# Author: Alan G IsaacX= [1,2,3,4,5,6]
I= [1,3,9,3,4,1]
F=np.bincount(I,X)
print(F)
66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆)
# Author: Fisher Wangw, h=256, 256I=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/2836621w, h=256, 256I=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 bytesI24=np.dot(I.astype(np.uint32),[1,256,65536])
# Count unique coloursn=len(np.unique(I24))
print(n)
67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)
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)
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? (★★★)
# Author: Jaime Fernández del RíoD=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_countsprint(D_means)
# Pandas solution as a reference due to more intuitive codeimportpandasaspdprint(pd.Series(D).groupby(S).mean())
69. How to get the diagonal of a dot product? (★★★)
# Author: Mathieu BlondelA=np.random.uniform(0,1,(5,5))
B=np.random.uniform(0,1,(5,5))
# Slow versionnp.diag(np.dot(A, B))
# Fast versionnp.sum(A*B.T, axis=1)
# Faster versionnp.einsum("ij,ji->i", A, B)
70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)
73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)
# Author: Nicolas P. Rougierfaces=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)
74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)
# Author: Jaime Fernández del RíoC=np.bincount([1,1,2,3,4,4,6])
A=np.repeat(np.arange(len(C)), C)
print(A)
75. How to compute averages using a sliding window over an array? (★★★)
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]) (★★★)
# Author: Joe Kington / Erik Rigtorpfromnumpy.libimportstride_tricksdefrolling(a, window):
shape= (a.size-window+1, window)
strides= (a.strides[0], a.strides[0])
returnstride_tricks.as_strided(a, shape=shape, strides=strides)
Z=rolling(np.arange(10), 3)
print(Z)
77. How to negate a boolean, or to change the sign of a float inplace? (★★★)
# Author: Nathaniel J. SmithZ=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)
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])? (★★★)
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])? (★★★)
# Author: Italmassov Kuanysh# based on distance function from previous questionP0=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) forp_iinp]))
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) (★★★)
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]]? (★★★)
# Author: Stefan van der WaltZ=np.arange(1,15,dtype=np.uint32)
R=stride_tricks.as_strided(Z,(11,4),(4,4))
print(R)
82. Compute a matrix rank (★★★)
# Author: Stefan van der WaltZ=np.random.uniform(0,1,(10,10))
U, S, V=np.linalg.svd(Z) # Singular Value Decompositionrank=np.sum(S>1e-10)
print(rank)
83. How to find the most frequent value in an array?
84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)
# Author: Chris BarkerZ=np.random.randint(0,5,(10,10))
n=3i=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)
85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)
# Author: Eric O. Lebigot# Note: only works for 2d array and value setting using indicesclassSymetric(np.ndarray):
def__setitem__(self, index, value):
i,j=indexsuper(Symetric, self).__setitem__((i,j), value)
super(Symetric, self).__setitem__((j,i), value)
defsymetric(Z):
returnnp.asarray(Z+Z.T-np.diag(Z.diagonal())).view(Symetric)
S=symetric(np.random.randint(0,10,(5,5)))
S[2,3] =42print(S)
86. Consider a set of p matrices wich 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)) (★★★)
# Author: Stefan van der Waltp, n=10, 20M=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.
87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)
# Author: Robert KernZ=np.ones((16,16))
k=4S=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=4windows=np.lib.stride_tricks.sliding_window_view(Z, (k, k))
S=windows[::k, ::k, ...].sum(axis=(-2, -1))
88. How to implement the Game of Life using numpy arrays? (★★★)
92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)
# Author: Ryan G.x=np.random.rand(int(5e7))
%timeitnp.power(x,3)
%timeitx*x*x%timeitnp.einsum('i,i,i->i',x,x,x)
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? (★★★)
94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)
# Author: Robert KernZ=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 ZU=Z[Z.max(axis=1) !=Z.min(axis=1),:]
print(U)
95. Convert a vector of ints into a matrix binary representation (★★★)
97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)
# 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 * Bnp.einsum('i,i', A, B) # np.inner(A, B)np.einsum('i,j->ij', A, B) # np.outer(A, B)
98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?
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. (★★★)
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). (★★★)
# Author: Jessica B. HamrickX=np.random.randn(100) # random 1D arrayN=1000# number of bootstrap samplesidx=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)