본문 바로가기
Programming/Machine Learning

100 numpy exercises

by NAMP 2019. 6. 5.

 

 

 

100 numpy exercises 실행

 

0. Install numpy package

numpy 패키지 설치

설치되지 않은 경우에만 실행하세요

In [2]:
!pip install numpy 
 
Collecting numpy
  Downloading https://files.pythonhosted.org/packages/ce/61/be72eee50f042db3acf0b1fb86650ad36d6c0d9be9fc29f8505d3b9d6baa/numpy-1.16.4-cp37-cp37m-win_amd64.whl (11.9MB)
Installing collected packages: numpy
Successfully installed numpy-1.16.4
 
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
 

1. Import the numpy package under the name np

numpy 패키지를 np 이름으로 사용

In [1]:
import numpy as np
 

2. Print the numpy version and the configuration

numpy 버전 및 설정 확인

In [4]:
print(np.__version__)
np.show_config()
 
1.16.4
blas_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
openblas_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
    libraries = ['openblas']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
    libraries = ['openblas']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
lapack_mkl_info:
  NOT AVAILABLE
openblas_lapack_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
    libraries = ['openblas']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
lapack_opt_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
    libraries = ['openblas']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
 

3. Create a null vector of size 10

10개의 0으로 채워진 null vector 생성

In [5]:
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 [7]:
Z = np.zeros((10,10))
print(Z.size, Z.itemsize)
print("%d bytes" % (Z.size * Z.itemsize))
 
100 8
800 bytes
 

5. How to get the documentation of the numpy add function from the command line?

커맨드 라인에서 numpy 실행

In [ ]:
%run `python -c "import numpy; numpy.info(numpy.add)"`
 

6. Create a null vector of size 10 but the fifth value which is 1

5번째 값은 1인 10개의 null vector 생성

인덱스는 0부터 시작하므로 5번째는 [4]

In [9]:
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

10 부터 49까지 범위의 vector 생성

arange 에서 마지막 값은 제외

In [10]:
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)

vector 역순 (첫번째 요소가 마지막이 됨)

In [12]:
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

0 부터 8까지의 3x3 matrix 생성

In [33]:
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]

[1,2,0,0,4,0] 요소에서 0 이 아닌 인덱스 찾기

In [35]:
nz = np.nonzero([1,2,0,0,4,0])
print(nz)
 
(array([0, 1, 4], dtype=int64),)
 

11. Create a 3x3 identity matrix

3x3 identity matrix 생성

In [36]:
Z = np.eye(3)
print(Z)
 
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
 

12. Create a 3x3x3 array with random values

무작위 값으로 3x3x3 배열 생성

In [37]:
Z = np.random.random((3,3,3))
print(Z)
 
[[[0.54516596 0.7096674  0.222761  ]
  [0.50984062 0.22814459 0.44314841]
  [0.77140907 0.29665585 0.80884159]]

 [[0.91353884 0.88474599 0.33247104]
  [0.98275175 0.52987005 0.14842723]
  [0.09089031 0.77097548 0.45771903]]

 [[0.71364622 0.77321246 0.62794807]
  [0.37778978 0.42401726 0.8171    ]
  [0.75050052 0.0532412  0.64381893]]]
 

13. Create a 10x10 array with random values and find the minimum and maximum values

무작위 값으로 10x10 배열 생성하고 최소값, 최대값 찾기

In [39]:
Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
 
0.007663438610730378 0.9924882867982604
 

14. Create a random vector of size 30 and find the mean value

평균값 구하기

In [40]:
Z = np.random.random(30)
m = Z.mean()
print(m)
 
0.3998415778443041
 

15. Create a 2d array with 1 on the border and 0 inside

  • 2차원 배열 생성 (10 x 10)
  • 전체값으로 1으로 채운다
  • 내부만 0으로 채운다
In [41]:
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 [47]:
Z = np.ones((5,5))
print(Z)
 
[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]]
In [48]:
Z = np.pad(Z, pad_width=1, mode='constant', constant_values =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.]]
 

17. What is the result of the following expression?

In [50]:
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 [51]:
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

  • checkerboard 패턴으로 1을 채운다
In [54]:
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?

  • (6,7,8) 형태 배열에서
  • 100번째 요소의 인덱스를 구한다
In [55]:
print(np.unravel_index(99, (6,7,8)))
 
(1, 5, 3)
 

21. Create a checkerboard 8x8 matrix using the tile function

  • (2,2)단위 메트릭스를 만들고
  • 단위 메트릭스를 (4,4)로 만든다.
In [60]:
np.array([[0,1], [1,0]])
Out[60]:
array([[0, 1],
       [1, 0]])
In [61]:
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 [62]:
Z = np.random.random((5,5))
Z = (Z - np.mean(Z)) / (np.std(Z))
print(Z)
 
[[ 1.27477456 -1.02838409  0.05005954  0.12758403 -1.61371813]
 [ 1.11395688 -0.4398255  -0.53958516 -1.41690706  2.0958647 ]
 [ 0.54657336  0.49061692 -0.33579681 -0.09211447  0.46802162]
 [ 2.20942414  0.58634411 -0.50696627 -1.59875474 -0.82443553]
 [ 0.20793242 -0.05866561 -0.41312883  0.77260471 -1.07547477]]
 

23. Create a custom dtype that describes a color as four unsigned bytes (RGBA)

In [64]:
color = np.dtype([("r", np.ubyte, 1),
                  ("g", np.ubyte, 1),
                  ("b", np.ubyte, 1),
                  ("a", np.ubyte, 1)])
print(color)
 
[('r', 'u1'), ('g', 'u1'), ('b', 'u1'), ('a', 'u1')]
 

24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product)

In [67]:
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
 
[[3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]]
In [69]:
Z = np.ones((5,3)) @ np.ones((3,2))
print(Z)
 
[[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.

  • 0부터 10까지 1차원 배열 생성
  • 3부터 8까지 음수로 변경
In [21]:
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?

  • sum 에서 2번째 파라미터는 시작값을 지정 (기본: 0)
  • np.sum에서 2번째 파라미터는 축을 지정
  • If axis is negative it counts from the last to the first axis.
In [13]:
print(sum(range(5), -1))
print(np.sum(range(5),-1))
 
9
10
In [8]:
?sum
 
Signature: sum(iterable, start=0, /)
Docstring:
Return the sum of a 'start' value (default: 0) plus an iterable of numbers

When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
Type:      builtin_function_or_method
 

27. Consider an integer vector Z, which of these expressions are legal?

In [33]:
Z = np.arange(11)

# Z**Z
print(Z @ Z)
print(2 << Z >> 2)
print(Z <- Z)
print(1j*Z)
print(Z/1/1)
# print(Z<Z>Z)
 
385
[  0   1   2   4   8  16  32  64 128 256 512]
[False False False False False False False False False False False]
[0. +0.j 0. +1.j 0. +2.j 0. +3.j 0. +4.j 0. +5.j 0. +6.j 0. +7.j 0. +8.j
 0. +9.j 0.+10.j]
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]
 

28. What are the result of the following expressions?

In [35]:
print(np.array(0))
 
0
In [38]:
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:\python37\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in true_divide
  """Entry point for launching an IPython kernel.
c:\python37\lib\site-packages\ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in floor_divide
  
 

29. How to round away from zero a float array ?

In [40]:
Z = np.random.uniform(-10, +10, 10)
print(Z)
print(np.copysign(np.ceil(np.abs(Z)),Z))
 
[-5.11924088 -6.6922455  -8.60420465 -6.89119733 -6.86848864  2.41621383
 -0.58502253 -4.42565887 -3.76206118 -7.70317563]
[-6. -7. -9. -7. -7.  3. -1. -5. -4. -8.]
 

30. How to find common values between two arrays?

In [42]:
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1, Z2))
 
[0 2 4 5]
In [43]:
np.random.randint(0,10,10)
Out[43]:
array([9, 4, 2, 8, 2, 3, 3, 7, 0, 5])
 

31. How to ignore all numpy warnings (not recommended)?

In [47]:
# Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0

# Back to sanity
_ = np.seterr(**defaults)

# An equivalent way, with a context manager:
with np.errstate(divide='ignore'):
    Z = np.ones(1) / 0
 

32. Is the following expressions true?

In [48]:
np.sqrt(-1) == np.emath.sqrt(-1)
 
c:\python37\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in sqrt
  """Entry point for launching an IPython kernel.
Out[48]:
False
 

33. How to get the dates of yesterday, today and tomorrow?

In [52]:
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
print(yesterday)
 
2019-05-29
In [54]:
today = np.datetime64('today', 'D')
print(today)
 
2019-05-30
In [55]:
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print(tomorrow)
 
2019-05-31
 

34. How to get all the dates corresponding to the month of July 2016

In [57]:
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 [59]:
A = np.ones(3)*1
B = np.ones(3)*2
C = np.ones(3)*3
np.add(A,B,out=B)
np.negative(A,out=A)
np.divide(A,2,out=A)
np.multiply(A,B,out=A)
Out[59]:
array([-1.5, -1.5, -1.5])
 

36. Extract the integer part of a random array using 5 different methods

In [60]:
Z = np.random.uniform(0,10,10)
print(Z)
 
[9.76881695 6.79573743 2.47912178 2.55439156 7.77579843 2.79669746
 0.83358508 2.56194617 2.03620389 8.31049469]
In [62]:
print(Z - Z%1)
print(np.floor(Z))
print(np.ceil(Z) - 1)
print(Z.astype(int))
print(np.trunc(Z))
 
[9. 6. 2. 2. 7. 2. 0. 2. 2. 8.]
[9. 6. 2. 2. 7. 2. 0. 2. 2. 8.]
[9. 6. 2. 2. 7. 2. 0. 2. 2. 8.]
[9 6 2 2 7 2 0 2 2 8]
[9. 6. 2. 2. 7. 2. 0. 2. 2. 8.]
 

37. Create a 5x5 matrix with row values ranging from 0 to 4

In [69]:
Z = np.zeros((5,5))
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.]]
In [70]:
Z += np.arange(5)
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.]]
 

38. Consider a generator function that generates 10 integers and use it to build an array

In [72]:
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

  • np.linspace를 사용하여 벡터 생성
  • [1:] 로 0 제외
In [77]:
np.linspace(0,1,11)
Out[77]:
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
In [78]:
np.linspace(0,1,11, endpoint=False)
Out[78]:
array([0.        , 0.09090909, 0.18181818, 0.27272727, 0.36363636,
       0.45454545, 0.54545455, 0.63636364, 0.72727273, 0.81818182,
       0.90909091])
In [79]:
np.linspace(0,1,11, endpoint=False)[1:]
Out[79]:
array([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 [82]:
Z = np.random.random(10)
Z.sort()
print(Z)
 
[0.1006629  0.21730061 0.24738972 0.61313481 0.65801442 0.67086713
 0.68705385 0.8769627  0.93169726 0.9489123 ]
 

41. How to sum a small array faster than np.sum?

  • 속도 비교를 위해 for 문을 추가하였습니다
In [103]:
%%time
Z = np.arange(10)
for i in range(999):
    np.sum(Z)
 
Wall time: 7 ms
In [104]:
%%time
Z = np.arange(10)
for i in range(999):
    np.add.reduce(Z)
 
Wall time: 3 ms
 

42. Consider two random array A and B, check if they are equal

  • 무작위 배열 A, B를 만들고
  • 같은지 비교
In [107]:
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)

print(A)
print(B)
 
[0 1 0 1 0]
[0 0 1 1 1]
In [113]:
# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(A,B)
print(equal)
 
False
In [114]:
# 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
 

43. Make an array immutable (read-only)

In [115]:
Z = np.zeros(10)
Z.flags.writeable = False
Z[0] = 1
 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-115-dcc5e7f145b5> in <module>
      1 Z = np.zeros(10)
      2 Z.flags.writeable = False
----> 3 Z[0] = 1

ValueError: assignment destination is read-only
 

44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates

  • cartesian coordinates : 직교 좌표계
  • polar coordinates : 극좌표계(極座標系)는 평면 위의 위치를 각도와 거리를 써서 나타내는 2차원 좌표계이다.
In [117]:
Z = np.random.random((10,2))
print(Z)
X, Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2+Y**2)
T = np.arctan2(Y,X)
print(R)
print(T)
 
[[0.63130677 0.5160934 ]
 [0.62010194 0.72033018]
 [0.44881716 0.58236965]
 [0.02198695 0.91300919]
 [0.30112797 0.20701647]
 [0.27336563 0.15726141]
 [0.40674    0.59247732]
 [0.10826374 0.10053791]
 [0.40777683 0.47849446]
 [0.39647274 0.05374447]]
[0.81541439 0.95047461 0.73524911 0.9132739  0.36542287 0.31537266
 0.71865625 0.14774609 0.62868028 0.40009887]
[0.68532107 0.86003236 0.91419461 1.54671913 0.60226704 0.52204366
 0.96918339 0.74841422 0.86502177 0.13473525]
 

45. Create random vector of size 10 and replace the maximum value by 0

In [118]:
Z = np.random.random(10)
print(Z)
 
[0.67289594 0.82662079 0.88660299 0.69185295 0.17258584 0.12246804
 0.71368396 0.5446969  0.72291678 0.21330961]
In [119]:
Z.argmax()
Out[119]:
2
In [120]:
Z[Z.argmax()] = 0
print(Z)
 
[0.67289594 0.82662079 0.         0.69185295 0.17258584 0.12246804
 0.71368396 0.5446969  0.72291678 0.21330961]
 

46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area

In [122]:
Z = np.zeros((5,5))
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.]]
In [123]:
Z = np.zeros((5,5), [('x', float), ('y', float)])
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.)]]
 

47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))

In [127]:
X = np.arange(8)
print(X)
 
[0 1 2 3 4 5 6 7]
In [128]:
Y = X + 0.5
print(Y)
 
[0.5 1.5 2.5 3.5 4.5 5.5 6.5 7.5]
In [129]:
np.subtract.outer(X, Y)
Out[129]:
array([[-0.5, -1.5, -2.5, -3.5, -4.5, -5.5, -6.5, -7.5],
       [ 0.5, -0.5, -1.5, -2.5, -3.5, -4.5, -5.5, -6.5],
       [ 1.5,  0.5, -0.5, -1.5, -2.5, -3.5, -4.5, -5.5],
       [ 2.5,  1.5,  0.5, -0.5, -1.5, -2.5, -3.5, -4.5],
       [ 3.5,  2.5,  1.5,  0.5, -0.5, -1.5, -2.5, -3.5],
       [ 4.5,  3.5,  2.5,  1.5,  0.5, -0.5, -1.5, -2.5],
       [ 5.5,  4.5,  3.5,  2.5,  1.5,  0.5, -0.5, -1.5],
       [ 6.5,  5.5,  4.5,  3.5,  2.5,  1.5,  0.5, -0.5]])
In [130]:
C = 1.0 / np.subtract.outer(X, Y)
print(C)
 
[[-2.         -0.66666667 -0.4        -0.28571429 -0.22222222 -0.18181818
  -0.15384615 -0.13333333]
 [ 2.         -2.         -0.66666667 -0.4        -0.28571429 -0.22222222
  -0.18181818 -0.15384615]
 [ 0.66666667  2.         -2.         -0.66666667 -0.4        -0.28571429
  -0.22222222 -0.18181818]
 [ 0.4         0.66666667  2.         -2.         -0.66666667 -0.4
  -0.28571429 -0.22222222]
 [ 0.28571429  0.4         0.66666667  2.         -2.         -0.66666667
  -0.4        -0.28571429]
 [ 0.22222222  0.28571429  0.4         0.66666667  2.         -2.
  -0.66666667 -0.4       ]
 [ 0.18181818  0.22222222  0.28571429  0.4         0.66666667  2.
  -2.         -0.66666667]
 [ 0.15384615  0.18181818  0.22222222  0.28571429  0.4         0.66666667
   2.         -2.        ]]
In [131]:
print(np.linalg.det(C))
 
3638.163637117973
 

48. Print the minimum and maximum representable value for each numpy scalar type

In [132]:
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 [135]:
# np.set_printoptions(threshold=np.nan)
Z = np.zeros((16,16))
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. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 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 [136]:
Z = np.arange(100)
print(Z)
 
[ 0  1  2  3  4  5  6  7  8  9 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
 96 97 98 99]
In [143]:
v = np.random.uniform(0, 100)
print(v)
 
25.467181723607435
In [144]:
index = (np.abs(Z-v)).argmin()
print(index)
 
25
 

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

In [150]:
position = ('position', [('x', float), ('y', float)])
color = ('color', [('r', float), ('g', float), ('b', float)])
Z = np.zeros(10, [position, color])
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.))]
 

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

In [152]:
Z = np.random.random((10, 2))
print(Z)
 
[[0.35944392 0.43770562]
 [0.35050923 0.7673866 ]
 [0.5532211  0.02535178]
 [0.32338157 0.09392259]
 [0.00436527 0.25173217]
 [0.12343201 0.76678662]
 [0.24181595 0.08298763]
 [0.86058013 0.01387648]
 [0.01311431 0.22100327]
 [0.66534074 0.22880009]]
In [154]:
X, Y = np.atleast_2d(Z[:, 0], Z[:, 1])
print(X, Y)
 
[[0.35944392 0.35050923 0.5532211  0.32338157 0.00436527 0.12343201
  0.24181595 0.86058013 0.01311431 0.66534074]] [[0.43770562 0.7673866  0.02535178 0.09392259 0.25173217 0.76678662
  0.08298763 0.01387648 0.22100327 0.22880009]]
In [155]:
D = np.sqrt((X-X.T)**2 + (Y-Y.T)**2)
print(D)
 
[[0.         0.32980202 0.45561528 0.3456693  0.40083285 0.4049641
  0.37371271 0.65632967 0.40853899 0.3704246 ]
 [0.32980202 0.         0.76922543 0.67401015 0.62105969 0.22707801
  0.69297631 0.90991747 0.64216047 0.62385439]
 [0.45561528 0.76922543 0.         0.2398503  0.59370937 0.85699725
  0.31669395 0.30757316 0.57445178 0.23229728]
 [0.3456693  0.67401015 0.2398503  0.         0.35591469 0.70194432
  0.08229534 0.54312951 0.33528387 0.36759762]
 [0.40083285 0.62105969 0.59370937 0.35591469 0.         0.52863785
  0.29130319 0.88863897 0.03195013 0.66137316]
 [0.4049641  0.22707801 0.85699725 0.70194432 0.52863785 0.
  0.69397105 1.05368924 0.55682084 0.76360629]
 [0.37371271 0.69297631 0.31669395 0.08229534 0.29130319 0.69397105
  0.         0.6226118  0.26711937 0.44792245]
 [0.65632967 0.90991747 0.30757316 0.54312951 0.88863897 1.05368924
  0.6226118  0.         0.87241035 0.29036283]
 [0.40853899 0.64216047 0.57445178 0.33528387 0.03195013 0.55682084
  0.26711937 0.87241035 0.         0.65227303]
 [0.3704246  0.62385439 0.23229728 0.36759762 0.66137316 0.76360629
  0.44792245 0.29036283 0.65227303 0.        ]]
In [157]:
# scipy 를 사용
!pip install scipy
 
Collecting scipy
  Downloading https://files.pythonhosted.org/packages/53/17/9dfd64540b6645fae581462ed2d1c8e680b7e946ca2789c5149693660392/scipy-1.3.0-cp37-cp37m-win_amd64.whl (30.3MB)
Requirement already satisfied: numpy>=1.13.3 in c:\python37\lib\site-packages (from scipy) (1.16.4)
Installing collected packages: scipy
Successfully installed scipy-1.3.0
 
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
In [158]:
import scipy
import scipy.spatial

Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)
 
[[0.         0.60193118 0.63408109 0.73278523 0.85703368 0.46689246
  0.31126298 0.47314665 0.24613569 0.28986582]
 [0.60193118 0.         0.56289413 0.23921012 0.82457245 0.7091384
  0.32327364 0.33128954 0.40650047 0.46843047]
 [0.63408109 0.56289413 0.         0.44111914 0.27146671 0.31166564
  0.42043523 0.25549216 0.42265605 0.34598241]
 [0.73278523 0.23921012 0.44111914 0.         0.66674874 0.68042006
  0.42170056 0.30646176 0.49501828 0.51098982]
 [0.85703368 0.82457245 0.27146671 0.66674874 0.         0.42765122
  0.68552619 0.52695887 0.6754784  0.58541093]
 [0.46689246 0.7091384  0.31166564 0.68042006 0.42765122 0.
  0.42911254 0.38872843 0.37231603 0.2721997 ]
 [0.31126298 0.32327364 0.42043523 0.42170056 0.68552619 0.42911254
  0.         0.18838291 0.08334137 0.16008781]
 [0.47314665 0.33128954 0.25549216 0.30646176 0.52695887 0.38872843
  0.18838291 0.         0.22804443 0.2109225 ]
 [0.24613569 0.40650047 0.42265605 0.49501828 0.6754784  0.37231603
  0.08334137 0.22804443 0.         0.10191438]
 [0.28986582 0.46843047 0.34598241 0.51098982 0.58541093 0.2721997
  0.16008781 0.2109225  0.10191438 0.        ]]
 

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

In [5]:
Z = np.arange(10, dtype=np.float32)
Z = Z.astype(np.int32, copy=False)
print(X)
 
[0 1 2 3 4 5 6 7 8 9]
 

54. How to read the following file

  • 파일에서 읽기
  • StringIO를 사용하여 텍스트 생성
In [6]:
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)
 
[[ 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?

In [8]:
Z = np.arange(9).reshape(3,3)
print(Z)
 
[[0 1 2]
 [3 4 5]
 [6 7 8]]
In [9]:
for index, value in np.ndenumerate(Z):
    print(index, value)
 
(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
In [10]:
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
 

56. Generate a generic 2D Gaussian-like array

In [13]:
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
print(X)
 
[[-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]]
In [15]:
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?

In [43]:
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. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 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. 1. 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.]]
In [72]:
np.random.choice(range(n*n), p)
Out[72]:
array([33, 30, 90])
 

58. Subtract the mean of each row of a matrix

In [77]:
X = np.random.rand(5, 10)
print(X)
 
[[0.65205801 0.24377795 0.44123382 0.72143672 0.22445801 0.66611252
  0.07442638 0.46738597 0.50190116 0.75889928]
 [0.7043295  0.41175855 0.89695957 0.43362857 0.17066369 0.81842534
  0.32075197 0.23119976 0.48835737 0.57266501]
 [0.49182075 0.65265082 0.69332903 0.07382969 0.50455196 0.05855297
  0.71257089 0.15484115 0.92289321 0.8406538 ]
 [0.975704   0.77122636 0.50636703 0.0159871  0.88851373 0.7063116
  0.03384616 0.33820162 0.74048716 0.20609815]
 [0.28246544 0.98257404 0.04445784 0.07276394 0.25812156 0.49298806
  0.83679085 0.55400323 0.64988359 0.14883812]]
In [78]:
Y = X - X.mean(axis=1, keepdims=True)
print(Y)
 
[[ 0.17688902 -0.23139103 -0.03393516  0.24626774 -0.25071097  0.19094354
  -0.4007426  -0.00778301  0.02673218  0.2837303 ]
 [ 0.19945557 -0.09311538  0.39208564 -0.07124537 -0.33421024  0.3135514
  -0.18412196 -0.27367417 -0.01651656  0.06779107]
 [-0.01874868  0.14208139  0.18275961 -0.43673974 -0.00601746 -0.45201646
   0.20200146 -0.35572827  0.41232378  0.33008437]
 [ 0.45742971  0.25295207 -0.01190726 -0.50228719  0.37023944  0.18803731
  -0.48442813 -0.18007267  0.22221287 -0.31217614]
 [-0.14982322  0.55028538 -0.38783083 -0.35952473 -0.17416711  0.06069939
   0.40450218  0.12171457  0.21759492 -0.28345054]]
 

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

In [128]:
Z = np.random.randint(0,10,(3,3))
print(Z)
# 2번째 컬럼으로 정렬
print(Z[Z[:,1].argsort()])
 
[[8 6 0]
 [8 2 1]
 [0 7 6]]
[[8 2 1]
 [8 6 0]
 [0 7 6]]
 

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

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

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

In [130]:
Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print(m)
 
0.6240864789806784
 

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

In [133]:
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])
 
[[0 1 2]
 [1 2 3]
 [2 3 4]]
 

63. Create an array class that has a name attribute

In [134]:
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')
        
Z = NameArray(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 [136]:
Z = np.ones(10)
I = np.random.randint(0, len(Z), 20)
print(I)
 
[8 7 1 8 7 5 1 4 8 0 4 6 4 5 7 9 3 4 8 8]
In [137]:
Z += np.bincount(I, minlength=len(Z))
print(Z)
 
[2. 3. 1. 2. 5. 3. 2. 4. 6. 2.]
In [138]:
np.add.at(Z, I, 1)
print(Z)
 
[ 3.  5.  1.  3.  9.  5.  3.  7. 11.  3.]
 

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

In [141]:
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 [154]:
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)
 
8
 

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

In [157]:
A = np.random.randint(0,10,(3,4,3,4))
In [158]:
sum = A.sum(axis=(-2,-1))
print(sum)
 
[[65 54 50 36]
 [66 67 63 66]
 [69 54 63 66]]
 

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 [160]:
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)
 
[0.65080942 0.40988188 0.39960778 0.46392945 0.48013648 0.37100542
 0.57942949 0.53093419 0.57192724 0.36469598]
In [165]:
!pip install pandas
 
Requirement already satisfied: pandas in c:\python37\lib\site-packages (0.24.2)
Requirement already satisfied: python-dateutil>=2.5.0 in c:\python37\lib\site-packages (from pandas) (2.8.0)
Requirement already satisfied: pytz>=2011k in c:\python37\lib\site-packages (from pandas) (2019.1)
Requirement already satisfied: numpy>=1.12.0 in c:\python37\lib\site-packages (from pandas) (1.16.4)
Requirement already satisfied: six>=1.5 in c:\python37\lib\site-packages (from python-dateutil>=2.5.0->pandas) (1.12.0)
 
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
In [166]:
import pandas as pd
print(pd.Series(D).groupby(S).mean())
 
0    0.650809
1    0.409882
2    0.399608
3    0.463929
4    0.480136
5    0.371005
6    0.579429
7    0.530934
8    0.571927
9    0.364696
dtype: float64
 

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

In [168]:
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[168]:
array([1.53075834, 0.49659608, 0.86302704, 1.87248966, 1.25305067])
 

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

  • [1,2,3,4,5] 벡터에서
  • 각 요소 사이에 0 을 3개씩 연속으로 넣은 새로운 벡터 생성
In [170]:
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 [171]:
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 [175]:
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 [176]:
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)
 
[( 5, 64) ( 5, 79) ( 6, 59) ( 6, 76) ( 9, 26) ( 9, 54) (14, 76) (14, 96)
 (15, 59) (15, 91) (20, 44) (20, 60) (26, 54) (32, 70) (32, 94) (38, 50)
 (38, 93) (44, 60) (47, 50) (47, 76) (50, 76) (50, 93) (59, 76) (59, 91)
 (64, 79) (66, 85) (66, 93) (70, 94) (76, 96) (85, 93)]
 

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

In [177]:
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 [178]:
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))
 
[ 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 [179]:
from numpy.lib import stride_tricks

def rolling(a, window):
    shape = (a.size - window + 1, window)
    strides = (a.itemsize, a.itemsize)
    return stride_tricks.as_strided(a, shape=shape, strides=strides)

Z = rolling(np.arange(10), 3)
print(Z)
 
[[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 [2]:
Z = np.random.randint(0, 2, 100)
print(Z)
 
[1 1 1 1 0 0 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 1 1 0 0
 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 1 0 1 1 1 0 1 0 1 1 0 0 1 0
 0 0 1 0 1 1 0 1 1 0 1 1 1 1 0 0 1 0 1 0 1 0 0 1 0 1]
In [3]:
np.logical_not(Z, out=Z)
Out[3]:
array([0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1,
       1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1,
       0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0,
       1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0])
In [4]:
Z = np.random.uniform(-1.0, 1.0, 100)
print(Z)
 
[-0.37352386  0.89853512  0.21674348 -0.51322124 -0.08601561  0.63095972
 -0.34324089 -0.38685344 -0.56715061 -0.54578971  0.46922865 -0.76522084
  0.38677347  0.06406137 -0.66991644  0.32238973  0.89224496 -0.02228018
 -0.95787879 -0.94524159 -0.58120407  0.77605763 -0.1476619  -0.52870961
 -0.47184934  0.91690657 -0.73055978  0.70487079 -0.40240332 -0.41282371
 -0.58356242 -0.67132384 -0.22397373 -0.27279146  0.99482357 -0.04034156
 -0.25951586  0.64018015  0.99204326  0.86560507 -0.06000957  0.67457467
  0.01021069 -0.26820679 -0.63682559  0.28101282  0.38873321  0.34508856
  0.69925383  0.69721679  0.54143392  0.24968103  0.57176896  0.96520127
  0.35985737  0.22411984  0.93318115  0.81951977  0.95408665 -0.58926708
 -0.61721133 -0.50177413 -0.04040807  0.76132249 -0.7951538   0.10713072
  0.50355972  0.6578766   0.31776337 -0.50645757  0.63956228 -0.68117132
  0.17620319 -0.22588727  0.51609584 -0.60780901  0.09637181 -0.91897693
  0.83748341  0.94215541  0.0215347  -0.64907502 -0.12966614  0.40469847
  0.84131031 -0.54986878 -0.98033222 -0.9033851  -0.49970099  0.11381573
 -0.57325667  0.29593491 -0.75640004  0.71975345 -0.53496801 -0.58453754
  0.69333858 -0.61649146 -0.5494603   0.75913803]
In [5]:
np.negative(Z, out=Z)
Out[5]:
array([ 0.37352386, -0.89853512, -0.21674348,  0.51322124,  0.08601561,
       -0.63095972,  0.34324089,  0.38685344,  0.56715061,  0.54578971,
       -0.46922865,  0.76522084, -0.38677347, -0.06406137,  0.66991644,
       -0.32238973, -0.89224496,  0.02228018,  0.95787879,  0.94524159,
        0.58120407, -0.77605763,  0.1476619 ,  0.52870961,  0.47184934,
       -0.91690657,  0.73055978, -0.70487079,  0.40240332,  0.41282371,
        0.58356242,  0.67132384,  0.22397373,  0.27279146, -0.99482357,
        0.04034156,  0.25951586, -0.64018015, -0.99204326, -0.86560507,
        0.06000957, -0.67457467, -0.01021069,  0.26820679,  0.63682559,
       -0.28101282, -0.38873321, -0.34508856, -0.69925383, -0.69721679,
       -0.54143392, -0.24968103, -0.57176896, -0.96520127, -0.35985737,
       -0.22411984, -0.93318115, -0.81951977, -0.95408665,  0.58926708,
        0.61721133,  0.50177413,  0.04040807, -0.76132249,  0.7951538 ,
       -0.10713072, -0.50355972, -0.6578766 , -0.31776337,  0.50645757,
       -0.63956228,  0.68117132, -0.17620319,  0.22588727, -0.51609584,
        0.60780901, -0.09637181,  0.91897693, -0.83748341, -0.94215541,
       -0.0215347 ,  0.64907502,  0.12966614, -0.40469847, -0.84131031,
        0.54986878,  0.98033222,  0.9033851 ,  0.49970099, -0.11381573,
        0.57325667, -0.29593491,  0.75640004, -0.71975345,  0.53496801,
        0.58453754, -0.69333858,  0.61649146,  0.5494603 , -0.75913803])
 

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 [6]:
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))
 
[ 3.5220262   9.80765952  7.1434123   3.78386577  7.78335601 10.7723591
 15.33470882 12.18302155 10.68421564  5.90356862]
 

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 [7]:
# 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]))
 
[[12.6859562   3.82578698  7.52583796  3.72769091  1.13614675  7.93796952
   7.4420555  11.16951205  8.54504781 12.17378221]
 [ 1.13578419 13.77981917  9.25735926  6.61493187 15.32963574  4.30610395
   9.49336954  3.8365241   0.13456488  1.96075954]
 [ 6.17177799  7.24124427  2.88036819  1.92701832 11.48570632  4.15176899
   4.44609324  2.12758874  1.5429675   6.61075091]
 [16.5725483   1.72055918  6.5342479   8.46724766 12.90794277  3.10564706
   3.35179302 12.13475747  3.40441052 17.00089912]
 [ 2.74111997 15.43107682 11.36991648 10.75434841 11.31808877  9.59183182
   6.43149908  6.70745489  4.83801502  2.20471821]
 [ 1.85608403 14.71223113 10.60496481  9.86300537 11.52926294  8.9074516
   6.42823158  5.87816237  4.33601507  1.31301096]
 [ 1.90148072 11.40519266  7.14634221  6.11866546 11.90018235  6.39143358
   5.89046031  2.22752673  2.67705271  2.42870854]
 [ 4.12391654 12.96833013  9.60013638 12.7093922   3.59801605 16.13888855
   0.92883141  6.17917352 12.26321608  4.21891051]
 [12.35642113  2.49058223  6.35832228  3.56323672  3.2576242   6.56201284
   5.24808445 10.31771678  6.75491889 12.02663202]
 [14.04141741  2.06494488  6.33115246  5.54163908  7.35738892  2.51819065
   1.56894565 10.98393872  2.47635911 14.03503854]]
 

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 [9]:
Z = np.random.randint(0, 10, (10,10))
shape = (5,5)
fill = 0
position = (1,1)
In [10]:
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)
In [11]:
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
In [12]:
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)
 
[[1 0 8 5 0 6 2 3 2 0]
 [6 2 2 0 8 3 8 4 8 6]
 [9 7 0 4 0 1 9 2 5 5]
 [1 5 9 1 4 6 5 9 7 7]
 [6 1 4 8 8 3 1 1 2 3]
 [6 8 8 1 0 4 5 9 8 7]
 [7 9 6 2 0 0 0 1 6 4]
 [4 6 1 9 6 7 1 6 6 4]
 [9 3 4 6 0 4 5 2 2 3]
 [3 2 5 6 7 0 9 6 4 6]]
[[0 0 0 0 0]
 [0 1 0 8 5]
 [0 6 2 2 0]
 [0 9 7 0 4]
 [0 1 5 9 1]]
 
c:\python37\lib\site-packages\ipykernel_launcher.py:8: 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.
  
 

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 [14]:
from numpy.lib import stride_tricks

Z = np.arange(1,15,dtype=np.uint32)
R = stride_tricks.as_strided(Z,(11,4),(4,4))
print(R)
 
[[ 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 [23]:
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)
 
10
 

83. How to find the most frequent value in an array?

  • 가장 빈도수가 높은 값은?
In [69]:
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 [70]:
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)
 
[[[[1 4 1]
   [4 4 4]
   [0 3 0]]

  [[4 1 1]
   [4 4 2]
   [3 0 2]]

  [[1 1 4]
   [4 2 1]
   [0 2 4]]

  [[1 4 4]
   [2 1 0]
   [2 4 3]]

  [[4 4 4]
   [1 0 4]
   [4 3 1]]

  [[4 4 2]
   [0 4 3]
   [3 1 1]]

  [[4 2 0]
   [4 3 4]
   [1 1 2]]

  [[2 0 2]
   [3 4 4]
   [1 2 0]]]


 [[[4 4 4]
   [0 3 0]
   [0 3 3]]

  [[4 4 2]
   [3 0 2]
   [3 3 2]]

  [[4 2 1]
   [0 2 4]
   [3 2 2]]

  [[2 1 0]
   [2 4 3]
   [2 2 4]]

  [[1 0 4]
   [4 3 1]
   [2 4 2]]

  [[0 4 3]
   [3 1 1]
   [4 2 4]]

  [[4 3 4]
   [1 1 2]
   [2 4 3]]

  [[3 4 4]
   [1 2 0]
   [4 3 3]]]


 [[[0 3 0]
   [0 3 3]
   [1 1 1]]

  [[3 0 2]
   [3 3 2]
   [1 1 1]]

  [[0 2 4]
   [3 2 2]
   [1 1 4]]

  [[2 4 3]
   [2 2 4]
   [1 4 1]]

  [[4 3 1]
   [2 4 2]
   [4 1 3]]

  [[3 1 1]
   [4 2 4]
   [1 3 4]]

  [[1 1 2]
   [2 4 3]
   [3 4 4]]

  [[1 2 0]
   [4 3 3]
   [4 4 4]]]


 [[[0 3 3]
   [1 1 1]
   [0 0 3]]

  [[3 3 2]
   [1 1 1]
   [0 3 0]]

  [[3 2 2]
   [1 1 4]
   [3 0 0]]

  [[2 2 4]
   [1 4 1]
   [0 0 0]]

  [[2 4 2]
   [4 1 3]
   [0 0 1]]

  [[4 2 4]
   [1 3 4]
   [0 1 2]]

  [[2 4 3]
   [3 4 4]
   [1 2 4]]

  [[4 3 3]
   [4 4 4]
   [2 4 2]]]


 [[[1 1 1]
   [0 0 3]
   [4 1 3]]

  [[1 1 1]
   [0 3 0]
   [1 3 2]]

  [[1 1 4]
   [3 0 0]
   [3 2 1]]

  [[1 4 1]
   [0 0 0]
   [2 1 0]]

  [[4 1 3]
   [0 0 1]
   [1 0 2]]

  [[1 3 4]
   [0 1 2]
   [0 2 2]]

  [[3 4 4]
   [1 2 4]
   [2 2 3]]

  [[4 4 4]
   [2 4 2]
   [2 3 1]]]


 [[[0 0 3]
   [4 1 3]
   [1 0 1]]

  [[0 3 0]
   [1 3 2]
   [0 1 1]]

  [[3 0 0]
   [3 2 1]
   [1 1 1]]

  [[0 0 0]
   [2 1 0]
   [1 1 3]]

  [[0 0 1]
   [1 0 2]
   [1 3 0]]

  [[0 1 2]
   [0 2 2]
   [3 0 1]]

  [[1 2 4]
   [2 2 3]
   [0 1 1]]

  [[2 4 2]
   [2 3 1]
   [1 1 0]]]


 [[[4 1 3]
   [1 0 1]
   [4 0 0]]

  [[1 3 2]
   [0 1 1]
   [0 0 4]]

  [[3 2 1]
   [1 1 1]
   [0 4 0]]

  [[2 1 0]
   [1 1 3]
   [4 0 2]]

  [[1 0 2]
   [1 3 0]
   [0 2 2]]

  [[0 2 2]
   [3 0 1]
   [2 2 2]]

  [[2 2 3]
   [0 1 1]
   [2 2 4]]

  [[2 3 1]
   [1 1 0]
   [2 4 0]]]


 [[[1 0 1]
   [4 0 0]
   [3 0 1]]

  [[0 1 1]
   [0 0 4]
   [0 1 3]]

  [[1 1 1]
   [0 4 0]
   [1 3 3]]

  [[1 1 3]
   [4 0 2]
   [3 3 4]]

  [[1 3 0]
   [0 2 2]
   [3 4 1]]

  [[3 0 1]
   [2 2 2]
   [4 1 4]]

  [[0 1 1]
   [2 2 4]
   [1 4 0]]

  [[1 1 0]
   [2 4 0]
   [4 0 2]]]]
 

85. Create a 2D array subclass such that Z[i,j] == Z[j,i]

In [71]:
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)
 
[[ 4  7 12  7 15]
 [ 7  0 13  6 17]
 [12 13  3 42  7]
 [ 7  6 42  8  9]
 [15 17  7  9  0]]
 

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))

In [72]:
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)
 
[[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 [73]:
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)
 
[[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 [76]:
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
In [79]:
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]]
 

89. How to get the n largest values of an array

In [81]:
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 [82]:
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 [83]:
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 [94]:
x = np.random.rand(int(5e1))

%timeit np.power(x,3)
%timeit x*x*x
%timeit np.einsum('i,i,i->i',x,x,x)
 
2.42 s ± 29.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
339 ms ± 5.17 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
198 ms ± 4.81 ms per loop (mean ± std. dev. of 7 runs, 1 loop 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 [95]:
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 5]
 

94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3])

In [96]:
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)
 
[[0 0 3]
 [2 0 2]
 [4 2 4]
 [0 1 2]
 [1 3 4]
 [4 2 0]
 [1 2 2]
 [0 4 3]
 [4 2 3]
 [2 1 4]]
[[0 0 3]
 [2 0 2]
 [4 2 4]
 [0 1 2]
 [1 3 4]
 [4 2 0]
 [1 2 2]
 [0 4 3]
 [4 2 3]
 [2 1 4]]
[[0 0 3]
 [2 0 2]
 [4 2 4]
 [0 1 2]
 [1 3 4]
 [4 2 0]
 [1 2 2]
 [0 4 3]
 [4 2 3]
 [2 1 4]]
In [ ]:
 
 

출처: https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises.ipynb

이것은 numpy 메일 링리스트, 스택 오버플로 및 numpy 문서에서 수집된 연습 모음입니다. 이 모음의 목표는 기존 및 신규 사용자 모두를 위한 빠른 참조를 제공하는 것 뿐만 아니라 가르치는 사람들을 위한 일련의 연습을 제공하는 것입니다.

오류가 있거나 문제를 해결할 수 있는 더 나은 방법이 있다고 생각되면 https://github.com/rougier/numpy-100 에서 이슈를 열어보십시오.

댓글