상세 컨텐츠

본문 제목

[ Numpy 100제 ] 31~40 번

Python/Numpy

by teang1995 2022. 1. 30. 14:56

본문

반응형

numpy 핸들링에 익숙해져야 한다고 생각해서.. 마침 누군가 잘 만들어둔 numpy 100제 문제가 있어 조금씩 풀어보려 한다.

문제 링크 : link
내 코드 : link

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

np.setarr(all="ignore")

# {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}

32. Is the following expressions true? (★☆☆)

np.sqrt(-1) == np.emath.sqrt(-1)

print(np.sqrt(-1)
# nan

print(np.emath.sqrt(-1)
# 1j

33. How to get the dates of yesterday, today and tomorrow? (★☆☆)

# for today
today = np.datetime64('today', 'D')
print("Today: ", today)

# for yesterday
yesterday = today - np.timedelta64(1, 'D')

print("Yestraday: ", yesterday)

# for tomorrow
tomorrow = today + np.timedelta64(1, 'D')

print("Tomorrow: ", tomorrow)

'''
Today:  2022-01-30
Yestraday:  2022-01-29
Tomorrow:  2022-01-31
'''

34. How to get all the dates corresponding to the month of July 2016? (★★☆)

print(np.arange('2016-07', '2016-08', dtype='datetime64[D]'))
'''
['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)? (★★☆)

A = np.ones(3)*1
B = np.ones(3)*2
np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)

# array([-1.5, -1.5, -1.5])

36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)

Z = np.random.uniform(0,10,10)

print(Z - Z%1) # Z%1 : 1로 Z의 요소들을 나눈 나머지.
print(Z // 1) 
print(np.floor(Z))
print(Z.astype(int))
print(np.trunc(Z))

# np.trunc # https://numpy.org/doc/stable/reference/generated/numpy.trunc.html
# The truncated value of the scalar x is the nearest integer i which is closer to zero than x is. 
# In short, the fractional part of the signed number x is discarded.

'''
[9. 5. 1. 4. 9. 4. 3. 8. 1. 8.]
[9. 5. 1. 4. 9. 4. 3. 8. 1. 8.]
[9. 5. 1. 4. 9. 4. 3. 8. 1. 8.]
[9 5 1 4 9 4 3 8 1 8]
[9. 5. 1. 4. 9. 4. 3. 8. 1. 8.]
'''

37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)

Z = np.zeros((5,5))
Z += np.arange(5)
print(Z)

# without broadcasting
Z = np.tile(np.arange(0, 5), (5,1))
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.]]
[[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]]
'''


```python
# np.tile 다시 보기?
a = np.arange(0, 3)
np.tile(a, (3, 3))
'''
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
       [0, 1, 2, 0, 1, 2, 0, 1, 2],
       [0, 1, 2, 0, 1, 2, 0, 1, 2]])
'''

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

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.]
# https://dojang.io/mod/page/view.php?id=2412
a = generate()
for _ in range(10):
    print(next(a))

'''
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 (★★☆)

Z = np.linspace(0,1,11,endpoint=False)[1:]
print(Z)

'''
[0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455
 0.63636364 0.72727273 0.81818182 0.90909091]
'''

```python
# about np.linspace
# numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)[source]

a = np.linspace(0, 10, 10, endpoint=True)
print(a)
# 10개의 숫자로 0~10까지를 10등분. 구간의 끝(endpoint) 포함.

b =a = np.linspace(0, 10, 10, endpoint=False)
print(b) 
# 10개의 숫자로 0~9까지를 10등분. 구간의 끝(endpoint) 미포함.

'''
[ 0.          1.11111111  2.22222222  3.33333333  4.44444444  5.55555556
  6.66666667  7.77777778  8.88888889 10.        ]
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
'''

40. Create a random vector of size 10 and sort it (★★☆)

Z =  np.random.normal(0, 10, 10)
print(Z)
print(sorted(Z))

[  4.55074002   5.16189442   9.84466275  -0.42380521   0.08125566
 -21.6399595   24.48054748  -3.52367648   2.00919851  -7.78866248]
[-21.639959497762916, -7.788662483200325, -3.5236764764648143, -0.42380520787354126, 0.08125565681761829, 2.009198510866457, 4.550740018032493, 5.161894421411884, 9.84466274888178, 24.48054748010984]

'Python > Numpy' 카테고리의 다른 글

[ Numpy 100제 ] 41 ~ 50 번  (0) 2022.01.30
[ Numpy 100제 ] 21 ~ 30 번  (0) 2021.10.06
[ Numpy 100제 ] 11 ~ 20 번  (0) 2021.10.02
[ Numpy 100제 ] 01 ~ 10 번  (0) 2021.10.01

관련글 더보기

댓글 영역