31. How to ignore all numpy warnings (not recommended)? (★☆☆)
# 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? (★☆☆)
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? (★☆☆)
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%1print(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)-1print(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 (★★☆)
38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)
deffunc():for i inrange(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')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
a = np.linspace(0,1,num=11,endpoint=False)[1:]print(a)