🐍Python/Numpy

[Numpy] Numpy 연습문제 61~70

728x90
반응형

61. Find the nearest value from a given value in an array (★★☆)

(hint: np.abs, argmin, flat)

In [9]:
Z = np.random.uniform(0,1,10)
z = 0.5 
m = Z.flat[np.abs(Z-z).argmin()]
print(m)
# flat은 펴주는 것 
0.5425169605826707

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

(hint: np.nditer)

In [31]:
A = np.arange(3).reshape(1,3)
B = np.arange(3).reshape(3,1)
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 (★★☆)

(hint: class method)

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)

In [39]:
Z = np.ones(10)
a = np.random.randint(0,len(Z),20)
np.add.at(Z,a,1)
print(a)
print(Z)
[7 7 3 6 9 4 3 0 6 6 5 4 5 8 0 5 1 0 3 7]
[4. 2. 1. 4. 3. 4. 4. 4. 2. 2.]

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

(hint: np.bincount)

In [42]:
X = [1,2,3,4,5,6]
I = [3,4,5,6,7,8]
F = np.bincount(I,X)
# I = Index라서 3번째부터 X의 원소가 들어감 
print(F)
[0. 0. 0. 1. 2. 3. 4. 5. 6.]

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

(hint: np.unique)

In [48]:
img = np.random.randint(0,2,(16,16,3)).astype(np.ubyte)
F = img[...,0]*(256*256) + img[...,1]*256 + img[...,2]
print(len(np.unique(F)))
8

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

(hint: sum(axis=(-2,-1)))

In [50]:
A = np.random.randint(0,10,(3,4,3,4))
A.sum(axis=(-2,-1))
Out[50]:
array([[49, 48, 67, 63],
       [62, 60, 51, 60],
       [60, 50, 59, 63]])

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)

In [79]:
D = np.random.uniform(0,1,100)
S = np.random.randint(0,10,100)
import pandas as pd
pd.Series(D).groupby(S).mean()
Out[79]:
0    0.344919
1    0.446985
2    0.466266
3    0.559847
4    0.580451
5    0.516268
6    0.493082
7    0.543462
8    0.403014
9    0.672358
dtype: float64

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

(hint: np.diag)

In [55]:
A = np.random.uniform(0,1,(5,5))
B = np.random.uniform(0,1,(5,5))

# 느림 
np.diag(np.dot(A,B))

# 가장 빠른 버젼
np.einsum('ij,ji->i',A,B) 
Out[55]:
array([1.40706923, 1.84596496, 1.3350442 , 1.15534832, 1.17558881])

70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)

(hint: array[::4])

In [75]:
import numpy as np

Z = np.array([1,2,3,4,5])
nz = 3
Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
# [::n] 처음부터 끝까지 n간격으로 
Z0[::nz+1] = Z
print(Z0)
[1. 0. 0. 0. 2. 0. 0. 0. 3. 0. 0. 0. 4. 0. 0. 0. 5.]


728x90
반응형