반응형

51. Create a structured array representing a position (x,y) and a color (r,g,b)

#hint: dtype
position = ('position', [ ('x', float, 1),('y', float, 1)])
color = ('color', [('r', float), ('g', float), ('b', float)])
data = np.zeros(10,[position, color])
print(data)

[((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))

((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))

((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))

((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))

((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))]

 

52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances

#hint: np.atleast_2d, T, np.sqrt
data = np.random.random((10,2))
print(data)

X, Y = np.atleast_2d(data[:, 0], data[:, 1])
print(X,'----',y)

D = np.sqrt((X-X.T)**2 + (Y-Y.T)**2)
print(D)

print('-'*10)

import scipy 
import scipy.spatial
data = np.random.random((10,2))
print(data)
D = scipy.spatial.distance.cdist(data,data)
print(D)

53. How to convert a float (32 bits) array into an integer (32 bits) in place?

#hint: view and [:] =
data = np.arange(10, dtype = np.float32)
data = data.astype(np.int32, copy = False)
print(data)

54. How to read the following file?

1, 2, 3, 4, 5
6,  ,  , 7, 8
 ,  , 9,10,11

#1, 2, 3, 4, 5
#6,  ,  , 7, 8
# ,  , 9,10,11
#hint: np.genfromtxt
from io import StringIO
s = StringIO("""1, 2, 3, 4, 5\n
                6,  ,  , 7, 8\n
                 ,  , 9,10,11\n""")
data = np.genfromtxt(s, delimiter=",", dtype =np.int)
print(data)

55. What is the equivalent of enumerate for numpy arrays?

#hint: np.ndenumerate, np.ndindex
Z = np.arange(9).reshape(3,3)
print(Z)

for idx, val in np.ndenumerate(Z):
    print(idx, val)
    
for idx in np.ndindex(Z.shape):
    print(idx, Z[idx]) 

56. Generate a generic 2D Gaussian-like array?

#hint: np.meshgrid, np.exp
X,Y = np.meshgrid(np.linspace(-1,1, 10) , np.linspace(-1,1,10))
print(X,Y)
D = np.sqrt(X*X+ Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-((D-mu) ** 2 / (2.0 * sigma**2)))
print(G)

57. How to randomly place p elements in a 2D array?

#hint: np.put, np.random.choice
n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p , replace= False),1)
print(Z)

print(np.random.choice(range(n*n), p))

58. Subtract the mean of each row of a matrix

#hint: mean(axis=,keepdims=)
X = np.random.rand(5,10)
print(X)
Y = X - X.mean(axis = 1, keepdims = True)
print(Y)
Y = X - X.mean(axis=1).reshape(-1,1)
print(Y)

59. How to sort an array by the nth column?

#hint: argsort
data = np.random.randint(0,10,(3,3))
print(data)
print(data[data[:,1].argsort()])

60. How to tell if a given 2D array has null columns?

#hint: any, ~
data = np.random.randint(0,10,(3,3))
print((~data.any(axis=0)).any())

 

61. Find the nearest value from a given value in an array?

#hint: np.abs, argmin, flat
data = np.random.uniform(0,1,10)
print(data)
z = 0.5
print(np.abs(data-z))
print(np.abs(data-z).argmin())
m = data.flat[np.abs(data-z).argmin()]
print(m)

[0.07982761 0.33920184 0.76591757 0.06233438 0.90342925 0.83787931 0.34956868 0.6211812 0.06168744 0.51835467]

[0.42017239 0.16079816 0.26591757 0.43766562 0.40342925 0.33787931 0.15043132 0.1211812 0.43831256 0.01835467]

9

0.5183546659345304 => flat위의 9번 째 자리의 수

 

62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator?

#hint: np.nditer
A = np.arange(3).reshape(3,1)
B = np.arange(3).reshape(1,3)
print(A, B)

it = np.nditer([A,B, None])

for x,y,z in it:
    z[...] = x+y

print(it.operands[2])    

63. Create an array class that has a name attribute

#hint: class method
class NameArray(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.info = getattr(obj,'name','no name')
data = NameArray(np.arange(10),'range_10')
print(data.name)

64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)?

#hint: np.bincount | np.add.at
data = np.ones(10)
I = np.random.randint(0, len(Z), 20)
print(I)

data += np.bincount(I, minlength = len(Z))
print(data)

np.add.at(data,I,1)
print(data)

65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)?

#hint: np.bincount
A = [1,2,3,4,5,6]
B = [1,3,9,3,4,1]
C = np.bincount(B,A)
print(C)

66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors

#hint: np.unique
w,h = 16,16
I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
F = I[...,0]*(256*256) + I[...,1]* 256 + I[...,2]
n = len(np.unique(F))
print(n)
print(np.unique(I))

67. Considering a four dimensions array, how to get sum over the last two axis at once?

#hint: sum(axis=(-2,-1))
A = np.random.randint(0,10,(3,4,3,4))
sum = A.sum(axis= (-2,-1))
print(sum)

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?

#hint: np.bincount
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

import pandas as pd
print(pd.Series(D).groupby(S).mean())

69. How to get the diagonal of a dot product?

#hint: np.diag
import numpy as np
A= np.random.uniform(0,1,(5,5))
B= np.random.uniform(0,1,(5,5))

print(np.diag(np.dot(A,B)))
print(np.sum(A * B.T, axis = 1))
print(np.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?

각 요소 사이에 0을 3개 입력 

#hint: array[::4]
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)

 

71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)?

#hint: array[:, :, None]
A = np.ones((5,5,3))
print(A)
B = 2 * np.ones((5,5))
print(B)
print(A * B[:,:,None])

72. How to swap two rows of an array?

#hint: array[[]] = array[[]]
A = np.arange(25).reshape(5,5)
print(A)
A[[0,1]] = A[[1,0]]
print(A)

73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles

#hint: repeat, np.roll, np.sort, view, np.unique
faces = np.random.randint(0,100,(10,3))
print(faces)
F = np.roll(faces.repeat(2, axis = 1), -1, axis = 1)
print(F)
F = F.reshape(len(F) * 3, 2)
print(F)
F = np.sort(F, axis = 1)
print(F)
G = F.view(dtype = [('p0', F.dtype),('p1',F.dtype)])
print(G)
G = np.unique(G)
print(G)

74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C?

A= np.bincount([1,1,2,3,4,4,6])

0 1 2 3 4 5 6 

0: 0은 없음 0

1: 1은 2번

2: 2는 1번

3: 3은 1번

4: 4은 2번

5: 5는 0번

6: 6은 1번

#hint: np.repeat
A= np.bincount([1,1,2,3,4,4,6])
print(A)
B = np.repeat(np.arange(len(A)),A)
print(B)

75. How to compute averages using a sliding window over an array? 

##hint: np.cumsum
def average(a, n = 3):
    ret = np.cumsum(a, dtype = float)
    ret[n:] = ret[n:]- ret[:-n]
    return ret[n-1:] / n
data = np.arange(20)
print(data)
print(average(data, n = 3))
반응형

'문제 > Numpy 100제' 카테고리의 다른 글

numpy exercise-4  (0) 2021.02.03
100 numpy exercises-2  (0) 2021.01.28
100 numpy exercises-1  (0) 2021.01.27

+ Recent posts