31. How to ignore all numpy warnings (not recommended)? (★☆☆)
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0
_ = 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? (★☆☆)
np.sqrt(-1) == np.emath.sqrt(-1)
import numpy as np
print (np.sqrt(-1))
print (np.emath.sqrt(-1))
nan
1j
D:\software\Anaconda\anaconda\lib\site-packages\ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in sqrt
33. How to get the dates of yesterday, today and tomorrow? (★☆☆)
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print (yesterday)
print (today)
print (tomorrow)
2019-03-06
2019-03-07
2019-03-09
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,3))
b = np.ones((3,3))*2
print (a)
print (b)
np.add(a,b,out = b)
print (b)
np.negative(np.divide(a,2,out = a),out = a)
np.multiply(b,a)
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
[[ 2. 2. 2.]
[ 2. 2. 2.]
[ 2. 2. 2.]]
[[ 3. 3. 3.]
[ 3. 3. 3.]
[ 3. 3. 3.]]
array([[-1.5, -1.5, -1.5],
[-1.5, -1.5, -1.5],
[-1.5, -1.5, -1.5]])
import numpy as np
x1 = np.arange(9.0).reshape((3, 3))
print (x1)
x2 = np.arange(3.0)
print (x2)
np.add(x1, x2)
[[ 0. 1. 2.]
[ 3. 4. 5.]
[ 6. 7. 8.]]
[ 0. 1. 2.]
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
import numpy as np
np.info(np.add)
add(x1, x2[, out])
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added. If ``x1.shape != x2.shape``, they must be
broadcastable to a common shape (which may be the shape of one or
the other).
Returns
-------
add : ndarray or scalar
The sum of `x1` and `x2`, element-wise. Returns a scalar if
both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.
Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
36. Extract the integer part of a random array using 5 different methods (★★☆)
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = a-a%1
print (b)
[ 5.68428275 6.46149097 1.74833976]
[ 5. 6. 1.]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = np.ceil(a)-1
print (b)
[ 5.73062958 4.83969552 2.19314448]
[ 5. 4. 2.]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = np.floor(a)
print (b)
[ 9.71114723 5.91123853 1.34266563]
[ 9. 5. 1.]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = a.astype(int)
print (b)
[ 4.57905255 6.74753994 8.26644833]
[4 6 8]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = np.trunc(a)
print (b)
[ 4.04213929 2.44154839 2.88524378]
[ 4. 2. 2.]
np.info(np.trunc)
trunc(x[, out])
Return the truncated value of the input, element-wise.
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.
Parameters
----------
x : array_like
Input data.
Returns
-------
y : ndarray or scalar
The truncated value of each element in `x`.
See Also
--------
ceil, floor, rint
Notes
-----
.. versionadded:: 1.3.0
Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.trunc(a)
array([-1., -1., -0., 0., 1., 1., 2.])
37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)
a = np.random.uniform(0,4,(5,5))
print (a)
[[ 3.68059573 2.89217004 3.93373932 1.89988404 3.31816657]
[ 3.12213533 0.07068453 0.18528237 1.6167759 0.82046869]
[ 0.37539813 1.50022606 3.3097724 2.90741528 0.01809809]
[ 3.70381829 0.75977331 1.75437137 1.53818723 3.51736614]
[ 1.40856755 0.92131058 3.86188851 0.8925987 3.67647075]]
a = np.zeros((5,5))
a += range (0,5)
print (a)
[[ 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 func():
for i in range(10):
yield i
a = np.fromiter(func(),dtype=float, count=-1)
print(a)
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
np.info(np.fromiter)
fromiter(iterable, dtype, count=-1)
Create a new 1-dimensional array from an iterable object.
Parameters
----------
iterable : iterable object
An iterable object providing data for the array.
dtype : data-type
The data-type of the returned array.
count : int, optional
The number of items to read from *iterable*. The default is -1,
which means all data is read.
Returns
-------
out : ndarray
The output array.
Notes
-----
Specify `count` to improve performance. It allows ``fromiter`` to
pre-allocate the output array, instead of resizing it on demand.
Examples
--------
>>> iterable = (x*x for x in range(5))
>>> np.fromiter(iterable, np.float)
array([ 0., 1., 4., 9., 16.])
39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)
np.info(np.linspace)
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
Return evenly spaced numbers over a specified interval.
Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop`].
The endpoint of the interval can optionally be excluded.
Parameters
----------
start : scalar
The starting value of the sequence.
stop : scalar
The end value of the sequence, unless `endpoint` is set to False.
In that case, the sequence consists of all but the last of ``num + 1``
evenly spaced samples, so that `stop` is excluded. Note that the step
size changes when `endpoint` is False.
num : int, optional
Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
If True, `stop` is the last sample. Otherwise, it is not included.
Default is True.
retstep : bool, optional
If True, return (`samples`, `step`), where `step` is the spacing
between samples.
dtype : dtype, optional
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
.. versionadded:: 1.9.0
Returns
-------
samples : ndarray
There are `num` equally spaced samples in the closed interval
``[start, stop]`` or the half-open interval ``[start, stop)``
(depending on whether `endpoint` is True or False).
step : float, optional
Only returned if `retstep` is True
Size of spacing between samples.
See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the
number of samples).
logspace : Samples uniformly distributed in log space.
Examples
--------
>>> np.linspace(2.0, 3.0, num=5)
array([ 2. , 2.25, 2.5 , 2.75, 3. ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([ 2. , 2.2, 2.4, 2.6, 2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1, y, 'o')
[]
>>> plt.plot(x2, y + 0.5, 'o')
[]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
a = np.linspace(0,1,num=11,endpoint=False)[1:]
print (a)
[ 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 (★★☆)
a = np.random.rand(10)
print (a)
print (sorted(a))
print (a)
[ 0.12869995 0.97825072 0.06260481 0.10932202 0.40136214 0.9808369
0.22498057 0.02908049 0.73547941 0.56994736]
[0.029080487074700012, 0.062604806619652731, 0.10932202350502584, 0.12869994535209672, 0.22498057120505621, 0.40136214089195832, 0.56994736490402698, 0.73547940896389297, 0.97825072255312717, 0.98083689547423358]
[ 0.12869995 0.97825072 0.06260481 0.10932202 0.40136214 0.9808369
0.22498057 0.02908049 0.73547941 0.56994736]
import numpy as np
b = np.random.random(10)
print