numpyの理解を深めるために100問エクササイズに挑戦してみました。
今回は31問目から40問目までです。
31. How to ignore all numpy warnings (not recommended)?
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0
_ = np.seterr(**defaults)
with np.errstate(all="ignore"):
np.arange(3) / 0
32. Is the following expressions true?
np.sqrt(-1) == np.emath.sqrt(-1)
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in sqrt
"""Entry point for launching an IPython kernel.
False
33. How to get the dates of yesterday, today and tomorrow?
yesterday = np.datetime64('today') - np.timedelta64(1)
print(yesterday)
today = np.datetime64('today')
print(today)
tomorrow = np.datetime64('today') + np.timedelta64(1)
print(tomorrow)
2021-06-09
2021-06-10
2021-06-11
34. How to get all the dates corresponding to the month of July 2016?
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)?
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)
print(Z // 1)
print(np.floor(Z))
print(Z.astype(int))
print(np.trunc(Z))
[5. 8. 6. 9. 3. 9. 4. 1. 5. 2.]
[5. 8. 6. 9. 3. 9. 4. 1. 5. 2.]
[5. 8. 6. 9. 3. 9. 4. 1. 5. 2.]
[5 8 6 9 3 9 4 1 5 2]
[5. 8. 6. 9. 3. 9. 4. 1. 5. 2.]
37. Create a 5×5 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]]
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.]
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]
40. Create a random vector of size 10 and sort it.
Z = np.random.random(10)
Z.sort()
print(Z)
[0.03129048 0.05040101 0.17924659 0.18225569 0.25945341 0.38218785
0.65797854 0.81519291 0.98469743 0.99617072]
次回は41〜50問目に挑戦してみます。