🐍Python/Numpy

[Numpy] Numpy 연습문제 51~60

728x90
반응형

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

(hint: dtype)

In [4]:
Z = np.zeros(10,[('position',[('x',float,1),
                             ('y',float,1)]),
                ('color', [('r',float,1),
                          ('g',float,1),
                          ('b',float,1)])])
Z
Out[4]:
array([((0., 0.), (0., 0., 0.)), ((0., 0.), (0., 0., 0.)),
       ((0., 0.), (0., 0., 0.)), ((0., 0.), (0., 0., 0.)),
       ((0., 0.), (0., 0., 0.)), ((0., 0.), (0., 0., 0.)),
       ((0., 0.), (0., 0., 0.)), ((0., 0.), (0., 0., 0.)),
       ((0., 0.), (0., 0., 0.)), ((0., 0.), (0., 0., 0.))],
      dtype=[('position', [('x', '<f8'), ('y', '<f8')]), ('color', [('r', '<f8'), ('g', '<f8'), ('b', '<f8')])])

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

(hint: np.atleast_2d, T, np.sqrt)

In [6]:
Z = np.random.random((10,2))
# np.atleat_2d : View inputs as arrays with at least two dimensions.
X,Y = np.atleast_2d(Z[:,0],Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)

#or
import scipy
import scipy.spatial

Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)
[[0.         0.25566774 0.18687418 0.82582169 0.81772819 0.91593726
  0.81838832 0.82137453 0.79258777 0.87856079]
 [0.25566774 0.         0.43733171 0.86658154 0.86634639 0.69713708
  0.82316996 0.6519955  0.66801261 0.65352963]
 [0.18687418 0.43733171 0.         0.78736075 0.77372945 1.05727402
  0.80745887 0.93089376 0.87372869 1.02527159]
 [0.82582169 0.86658154 0.78736075 0.         0.02667629 0.92310127
  0.12051373 0.68395204 0.5291463  0.93438994]
 [0.81772819 0.86634639 0.77372945 0.02667629 0.         0.94193512
  0.144917   0.70356771 0.5495584  0.95208941]
 [0.91593726 0.69713708 1.05727402 0.92310127 0.94193512 0.
  0.81042233 0.24118371 0.39805596 0.05578258]
 [0.81838832 0.82316996 0.80745887 0.12051373 0.144917   0.81042233
  0.         0.56990556 0.41372989 0.82459279]
 [0.82137453 0.6519955  0.93089376 0.68395204 0.70356771 0.24118371
  0.56990556 0.         0.15687549 0.26243803]
 [0.79258777 0.66801261 0.87372869 0.5291463  0.5495584  0.39805596
  0.41372989 0.15687549 0.         0.41707579]
 [0.87856079 0.65352963 1.02527159 0.93438994 0.95208941 0.05578258
  0.82459279 0.26243803 0.41707579 0.        ]]
[[0.         0.26235894 0.51661562 0.9945112  1.09831166 0.28311656
  0.76115999 0.82497443 0.63798242 0.15513942]
 [0.26235894 0.         0.35414559 0.73290838 0.85702163 0.10437975
  0.54625866 0.67014743 0.40355442 0.13270344]
 [0.51661562 0.35414559 0.         0.70899049 0.63188647 0.26084863
  0.74254841 0.31835119 0.58589798 0.46303203]
 [0.9945112  0.73290838 0.70899049 0.         0.44677457 0.74858533
  0.44461623 0.78141811 0.42757189 0.84893261]
 [1.09831166 0.85702163 0.63188647 0.44677457 0.         0.81530408
  0.83151294 0.50541759 0.74582718 0.98972504]
 [0.28311656 0.10437975 0.26084863 0.74858533 0.81530408 0.
  0.62074365 0.57918711 0.46951339 0.2025172 ]
 [0.76115999 0.54625866 0.74254841 0.44461623 0.83151294 0.62074365
  0.         0.96612072 0.15755507 0.60727551]
 [0.82497443 0.67014743 0.31835119 0.78141811 0.50541759 0.57918711
  0.96612072 0.         0.82077898 0.78134498]
 [0.63798242 0.40355442 0.58589798 0.42757189 0.74582718 0.46951339
  0.15755507 0.82077898 0.         0.48292037]
 [0.15513942 0.13270344 0.46303203 0.84893261 0.98972504 0.2025172
  0.60727551 0.78134498 0.48292037 0.        ]]

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

(hint: astype(copy=False))

In [7]:
Z = np.arange(10,dtype=np.float32)
Z = Z.astype(np.int32,copy=False)
# copy = False : the input array is returned instead of a copy.
print(Z)
[0 1 2 3 4 5 6 7 8 9]

54. How to read the following file? (★★☆)

(hint: np.genfromtxt)

1, 2, 3, 4, 5
6,  ,  , 7, 8
 ,  , 9,10,11
In [13]:
from io import StringIO

# fake file
s = StringIO("""1, 2, 3, 4, 5\n
                6,  ,  , 7, 8\n
                 ,  , 9,10,11\n""")

Z = np.genfromtxt(s,delimiter=",",dtype=np.int)
print(Z)

# genfromtxt : Load data from a text file, with missing values handled as specified.
[[ 1  2  3  4  5]
 [ 6 -1 -1  7  8]
 [-1 -1  9 10 11]]

55. What is the equivalent of enumerate for numpy arrays? (★★☆)

(hint: np.ndenumerate, np.ndindex)

In [16]:
Z = np.arange(9).reshape(3,3)
# np.ndenumerate : Multidimensional index iterator. ( 다차원 index 반환)
for index, value in np.ndenumerate(Z):
    print(index,value)
for index in np.ndindex(Z.shape):
    print(index,Z[index])
    
# np.ndindex : An N-dimensional iterator object to index arrays. ( 다차원 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 (★★☆)

(hint: np.meshgrid, np.exp)

In [19]:
X,Y = np.meshgrid(np.linspace(-1,1,10),np.linspace(-1,1,10))
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)
[[0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.60279818
  0.57375342 0.51979489 0.44822088 0.36787944]
 [0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.73444367
  0.69905581 0.63331324 0.54610814 0.44822088]
 [0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.85172308
  0.81068432 0.73444367 0.63331324 0.51979489]
 [0.57375342 0.69905581 0.81068432 0.89483932 0.9401382  0.9401382
  0.89483932 0.81068432 0.69905581 0.57375342]
 [0.60279818 0.73444367 0.85172308 0.9401382  0.98773022 0.98773022
  0.9401382  0.85172308 0.73444367 0.60279818]
 [0.60279818 0.73444367 0.85172308 0.9401382  0.98773022 0.98773022
  0.9401382  0.85172308 0.73444367 0.60279818]
 [0.57375342 0.69905581 0.81068432 0.89483932 0.9401382  0.9401382
  0.89483932 0.81068432 0.69905581 0.57375342]
 [0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.85172308
  0.81068432 0.73444367 0.63331324 0.51979489]
 [0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.73444367
  0.69905581 0.63331324 0.54610814 0.44822088]
 [0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.60279818
  0.57375342 0.51979489 0.44822088 0.36787944]]

57. How to randomly place p elements in a 2D array? (★★☆)

(hint: np.put, np.random.choice)

In [26]:
n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
print(Z)

# np.put : Replaces specified elements of an array with given values.
# np.random.choice : Generates a random sample from a given 1-D array
[[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.]
 [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. 1. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

58. Subtract the mean of each row of a matrix (★★☆)

(hint: mean(axis=,keepdims=))

In [30]:
X = np.random.rand(5,10)

Y = X - X.mean(axis=1,keepdims=True)       # axis=1은 행선택 , keepdims로 차원 유지
print(Y)
[[ 0.31638826  0.49414131  0.1330871  -0.29121452  0.0039964  -0.22185645
  -0.06949495  0.01420251 -0.09311973 -0.28612993]
 [ 0.50992792 -0.32241525 -0.10077528  0.43745556 -0.3663575  -0.21853251
  -0.28525541 -0.29006716  0.30986625  0.32615338]
 [ 0.26316176 -0.08979555 -0.07802327 -0.23652644 -0.10012807  0.37880652
  -0.50513801  0.03602345  0.32645922  0.00516039]
 [ 0.00670928  0.38054221  0.10143331 -0.41960196 -0.32585495 -0.08739221
   0.56777825  0.38592094 -0.39262392 -0.21691094]
 [ 0.38889876  0.08320851  0.14833648 -0.48849513  0.00275739  0.14517884
   0.37553888 -0.53551919 -0.40751486  0.28761032]]

59. How to sort an array by the nth column? (★★☆)

(hint: argsort)

In [45]:
Z = np.random.randint(0,10,(3,3))
print(Z)
print(Z[Z[:,1].argsort()])

## 행의 1번째 성분의 크기를 보고 순서대로 정렬한다. ( 3,7,1   -> 1, 3, 7)  
[[2 7 6]
 [0 5 2]
 [6 7 5]]
[[0 5 2]
 [2 7 6]
 [6 7 5]]

60. How to tell if a given 2D array has null columns? (★★☆)

(hint: any, ~)

In [41]:
Z = np.random.randint(0,3,(3,10))
print(Z)
print((~Z.any(axis=0)).any())

# null 인 column이 있는지 ( 전부 0)
[[0 0 0 2 2 0 2 0 2 2]
 [2 0 2 1 2 1 2 0 1 1]
 [1 0 2 1 0 1 2 0 2 0]]
True


728x90
반응형