python 100_Numpy_exercises (1)

100 numpy exercises

This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow and in the numpy documentation. The goal of this collection is to offer a quick reference for both old and new users but also to provide a set of exercises for those who teach.

If you find an error or think you’ve a better way to solve some of them, feel free to open an issue at https://github.com/rougier/numpy-100

import sys 
import numpy as np
print (sys.version)
print (np.__version__)
3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]
1.12.1

1. Import the numpy package under the name np (★☆☆)

import numpy as np

2. Print the numpy version and the configuration (★☆☆)

print (np.__version__)
print (np.show_config())
1.12.1
blas_mkl_info:
    libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
    library_dirs = ['D:/software/Anaconda/anaconda\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['D:/software/Anaconda/anaconda\\Library\\include']
blas_opt_info:
    libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
    library_dirs = ['D:/software/Anaconda/anaconda\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['D:/software/Anaconda/anaconda\\Library\\include']
lapack_mkl_info:
    libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
    library_dirs = ['D:/software/Anaconda/anaconda\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['D:/software/Anaconda/anaconda\\Library\\include']
lapack_opt_info:
    libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
    library_dirs = ['D:/software/Anaconda/anaconda\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['D:/software/Anaconda/anaconda\\Library\\include']
None

3. Create a null vector of size 10 (★☆☆)

a = np.zeros(10)
a
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
a = np.zeros(10)
print (a) 
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

4. How to find the memory size of any array (★☆☆)

help(np.zeros)
Help on built-in function zeros in module numpy.core.multiarray:

zeros(...)
    zeros(shape, dtype=float, order='C')
    
    Return a new array of given shape and type, filled with zeros.
    
    Parameters
    ----------
    shape : int or sequence of ints
        Shape of the new array, e.g., ``(2, 3)`` or ``2``.
    dtype : data-type, optional
        The desired data-type for the array, e.g., `numpy.int8`.  Default is
        `numpy.float64`.
    order : {'C', 'F'}, optional
        Whether to store multidimensional data in C- or Fortran-contiguous
        (row- or column-wise) order in memory.
    
    Returns
    -------
    out : ndarray
        Array of zeros with the given shape, dtype, and order.
    
    See Also
    --------
    zeros_like : Return an array of zeros with shape and type of input.
    ones_like : Return an array of ones with shape and type of input.
    empty_like : Return an empty array with shape and type of input.
    ones : Return a new array setting values to one.
    empty : Return a new uninitialized array.
    
    Examples
    --------
    >>> np.zeros(5)
    array([ 0.,  0.,  0.,  0.,  0.])
    
    >>> np.zeros((5,), dtype=np.int)
    array([0, 0, 0, 0, 0])
    
    >>> np.zeros((2, 1))
    array([[ 0.],
           [ 0.]])
    
    >>> s = (2,2)
    >>> np.zeros(s)
    array([[ 0.,  0.],
           [ 0.,  0.]])
    
    >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
    array([(0, 0), (0, 0)],
          dtype=[('x', '<i4'), ('y', '<i4')])
a = np.zeros((10,10))
print ('memory is %d bytes'%(a.size * a.itemsize))
memory is 800 bytes

5. How to get the documentation of the numpy add function from the command line? (★☆☆)

print (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.]])
None
print (np.info(np.zeros))
zeros(shape, dtype=float, order='C')

Return a new array of given shape and type, filled with zeros.

Parameters
----------
shape : int or sequence of ints
    Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
    The desired data-type for the array, e.g., `numpy.int8`.  Default is
    `numpy.float64`.
order : {'C', 'F'}, optional
    Whether to store multidimensional data in C- or Fortran-contiguous
    (row- or column-wise) order in memory.

Returns
-------
out : ndarray
    Array of zeros with the given shape, dtype, and order.

See Also
--------
zeros_like : Return an array of zeros with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
empty_like : Return an empty array with shape and type of input.
ones : Return a new array setting values to one.
empty : Return a new uninitialized array.

Examples
--------
>>> np.zeros(5)
array([ 0.,  0.,  0.,  0.,  0.])

>>> np.zeros((5,), dtype=np.int)
array([0, 0, 0, 0, 0])

>>> np.zeros((2, 1))
array([[ 0.],
       [ 0.]])

>>> s = (2,2)
>>> np.zeros(s)
array([[ 0.,  0.],
       [ 0.,  0.]])

>>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
array([(0, 0), (0, 0)],
      dtype=[('x', '<i4'), ('y', '<i4')])
None

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

a = np.zeros(10)
a[4] = 1
print(a)
[ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]

7. Create a vector with values ranging from 10 to 49 (★☆☆)

a = np.arange(10,50)
print (a)
[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) (★☆☆)

a = np.arange (1,10)
b = a[::-1]
c = reversed(a)
print (b)
list(c)

[9 8 7 6 5 4 3 2 1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]

9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)

a = np.arange(0,9).reshape(3,3)
print(a)
[[0 1 2]
 [3 4 5]
 [6 7 8]]

10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)

a = [1,2,0,0,4,0]

for i,j in enumerate(a):    
#     print(i,j)
    if j != 0:
        print (i)
            
0
1
4
a = [1,2,0,0,4,0]
i = 0
for j in a:
    if j != 0:
        print (i)
    i += 1
0
1
4
a = [1,2,0,0,4,0]
b = np.nonzero(a)
print (b)
(array([0, 1, 4], dtype=int64),)

11. Create a 3x3 identity matrix (★☆☆)

a = np.eye(3)
b = np.identity(3)
print (a)
print ('b = ',b)
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]
b =  [[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]

12. Create a 3x3x3 array with random values (★☆☆)

a = np.random.random((3,3,3))
print (a)
[[[ 0.61054997  0.50222147  0.88645458]
  [ 0.79492527  0.74168231  0.7884879 ]
  [ 0.91418596  0.16999726  0.02094797]]

 [[ 0.95386281  0.78551487  0.06598779]
  [ 0.94186884  0.01704988  0.78918593]
  [ 0.75975801  0.64948246  0.68900774]]

 [[ 0.97829308  0.06265366  0.47905279]
  [ 0.28596686  0.78195905  0.84720389]
  [ 0.3215024   0.14873899  0.61854801]]]
help (np.random.random)
Help on built-in function random_sample:

random_sample(...) method of mtrand.RandomState instance
    random_sample(size=None)
    
    Return random floats in the half-open interval [0.0, 1.0).
    
    Results are from the "continuous uniform" distribution over the
    stated interval.  To sample :math:`Unif[a, b), b > a` multiply
    the output of `random_sample` by `(b-a)` and add `a`::
    
      (b - a) * random_sample() + a
    
    Parameters
    ----------
    size : int or tuple of ints, optional
        Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
        ``m * n * k`` samples are drawn.  Default is None, in which case a
        single value is returned.
    
    Returns
    -------
    out : float or ndarray of floats
        Array of random floats of shape `size` (unless ``size=None``, in which
        case a single float is returned).
    
    Examples
    --------
    >>> np.random.random_sample()
    0.47108547995356098
    >>> type(np.random.random_sample())
    <type 'float'>
    >>> np.random.random_sample((5,))
    array([ 0.30220482,  0.86820401,  0.1654503 ,  0.11659149,  0.54323428])
    
    Three-by-two array of random numbers from [-5, 0):
    
    >>> 5 * np.random.random_sample((3, 2)) - 5
    array([[-3.99149989, -0.52338984],
           [-2.99091858, -0.79479508],
           [-1.23204345, -1.75224494]])

13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)

a = np.random.random((10,10))
print (a)
print (a.min())
print ('max of a is',a.max())
[[ 0.85378968  0.30052792  0.32897667  0.94946617  0.74232545  0.80557923
   0.79320127  0.55738967  0.38255965  0.92740366]
 [ 0.38159618  0.6130852   0.73901066  0.21990684  0.53345964  0.33624883
   0.21960623  0.63032741  0.68758925  0.82613226]
 [ 0.81108133  0.92724417  0.42407872  0.31700689  0.43695886  0.13668786
   0.04224526  0.95037377  0.8809035   0.04733669]
 [ 0.86613302  0.63538354  0.290962    0.27933519  0.31280727  0.67461509
   0.0333739   0.49183439  0.48660695  0.26586315]
 [ 0.23504729  0.56197987  0.33606867  0.69701247  0.23681327  0.87369029
   0.65820313  0.78892748  0.44440871  0.94360498]
 [ 0.62877966  0.03906378  0.36061694  0.25047283  0.03409716  0.84672207
   0.22631517  0.36896234  0.03440796  0.63139765]
 [ 0.57096166  0.04147649  0.79510113  0.00399643  0.04466396  0.20731974
   0.64053489  0.27042887  0.76202365  0.57476975]
 [ 0.89348703  0.63854849  0.66133083  0.59096867  0.44261789  0.83770698
   0.97985279  0.41857113  0.46557929  0.43504438]
 [ 0.98083536  0.93685228  0.64625055  0.58708219  0.8616489   0.12019448
   0.32139979  0.37673523  0.14425146  0.54616171]
 [ 0.80033371  0.6438858   0.82821959  0.68635717  0.84602502  0.40293086
   0.32902467  0.77837641  0.73478222  0.09150157]]
0.00399643128487
max of a is 0.980835358339

14. Create a random vector of size 30 and find the mean value (★☆☆)

a = np.random.random((30))
print (a)
print (a.mean())
[ 0.18725256  0.89943202  0.94068962  0.24376474  0.35282234  0.65200619
  0.14536832  0.80337721  0.85198868  0.49479442  0.20706317  0.19614999
  0.21535567  0.48723499  0.07211702  0.51191561  0.01007843  0.25561316
  0.8716462   0.00586077  0.14670653  0.5038858   0.08751921  0.97045517
  0.39199647  0.97278592  0.47808886  0.61774231  0.87698523  0.68255081]
0.471108247461
a = np.random.randint(1,10)
print (a)
3
a = np.random.randn(2,3)
print (a)
[[ 0.14214468  2.0841094  -0.29188438]
 [ 1.3486413  -0.87109539  0.10313184]]
a = np.random.randint(low=2,high=5,size=(2,3))
print (a)
[[3 4 3]
 [4 2 4]]
help(np.random.randint)
Help on built-in function randint:

randint(...) method of mtrand.RandomState instance
    randint(low, high=None, size=None, dtype='l')
    
    Return random integers from `low` (inclusive) to `high` (exclusive).
    
    Return random integers from the "discrete uniform" distribution of
    the specified dtype in the "half-open" interval [`low`, `high`). If
    `high` is None (the default), then results are from [0, `low`).
    
    Parameters
    ----------
    low : int
        Lowest (signed) integer to be drawn from the distribution (unless
        ``high=None``, in which case this parameter is one above the
        *highest* such integer).
    high : int, optional
        If provided, one above the largest (signed) integer to be drawn
        from the distribution (see above for behavior if ``high=None``).
    size : int or tuple of ints, optional
        Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
        ``m * n * k`` samples are drawn.  Default is None, in which case a
        single value is returned.
    dtype : dtype, optional
        Desired dtype of the result. All dtypes are determined by their
        name, i.e., 'int64', 'int', etc, so byteorder is not available
        and a specific precision may have different C types depending
        on the platform. The default value is 'np.int'.
    
        .. versionadded:: 1.11.0
    
    Returns
    -------
    out : int or ndarray of ints
        `size`-shaped array of random integers from the appropriate
        distribution, or a single such random int if `size` not provided.
    
    See Also
    --------
    random.random_integers : similar to `randint`, only for the closed
        interval [`low`, `high`], and 1 is the lowest value if `high` is
        omitted. In particular, this other one is the one to use to generate
        uniformly distributed discrete non-integers.
    
    Examples
    --------
    >>> np.random.randint(2, size=10)
    array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
    >>> np.random.randint(1, size=10)
    array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    
    Generate a 2 x 4 array of ints between 0 and 4, inclusive:
    
    >>> np.random.randint(5, size=(2, 4))
    array([[4, 0, 2, 1],
           [3, 2, 2, 0]])

15. Create a 2d array with 1 on the border and 0 inside (★☆☆)

a = np.zeros((10,10))
a[1:-1,1:-1]=1
print (a)
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  1.  1.  1.  1.  1.  1.  1.  1.  0.]
 [ 0.  1.  1.  1.  1.  1.  1.  1.  1.  0.]
 [ 0.  1.  1.  1.  1.  1.  1.  1.  1.  0.]
 [ 0.  1.  1.  1.  1.  1.  1.  1.  1.  0.]
 [ 0.  1.  1.  1.  1.  1.  1.  1.  1.  0.]
 [ 0.  1.  1.  1.  1.  1.  1.  1.  1.  0.]
 [ 0.  1.  1.  1.  1.  1.  1.  1.  1.  0.]
 [ 0.  1.  1.  1.  1.  1.  1.  1.  1.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]

16. How to add a border (filled with 0’s) around an existing array? (★☆☆)

np.info(np.pad)
 pad(array, pad_width, mode, **kwargs)

Pads an array.

Parameters
----------
array : array_like of rank N
    Input array
pad_width : {sequence, array_like, int}
    Number of values padded to the edges of each axis.
    ((before_1, after_1), ... (before_N, after_N)) unique pad widths
    for each axis.
    ((before, after),) yields same before and after pad for each axis.
    (pad,) or int is a shortcut for before = after = pad width for all
    axes.
mode : str or function
    One of the following string values or a user supplied function.

    'constant'
        Pads with a constant value.
    'edge'
        Pads with the edge values of array.
    'linear_ramp'
        Pads with the linear ramp between end_value and the
        array edge value.
    'maximum'
        Pads with the maximum value of all or part of the
        vector along each axis.
    'mean'
        Pads with the mean value of all or part of the
        vector along each axis.
    'median'
        Pads with the median value of all or part of the
        vector along each axis.
    'minimum'
        Pads with the minimum value of all or part of the
        vector along each axis.
    'reflect'
        Pads with the reflection of the vector mirrored on
        the first and last values of the vector along each
        axis.
    'symmetric'
        Pads with the reflection of the vector mirrored
        along the edge of the array.
    'wrap'
        Pads with the wrap of the vector along the axis.
        The first values are used to pad the end and the
        end values are used to pad the beginning.
    <function>
        Padding function, see Notes.
stat_length : sequence or int, optional
    Used in 'maximum', 'mean', 'median', and 'minimum'.  Number of
    values at edge of each axis used to calculate the statistic value.

    ((before_1, after_1), ... (before_N, after_N)) unique statistic
    lengths for each axis.

    ((before, after),) yields same before and after statistic lengths
    for each axis.

    (stat_length,) or int is a shortcut for before = after = statistic
    length for all axes.

    Default is ``None``, to use the entire axis.
constant_values : sequence or int, optional
    Used in 'constant'.  The values to set the padded values for each
    axis.

    ((before_1, after_1), ... (before_N, after_N)) unique pad constants
    for each axis.

    ((before, after),) yields same before and after constants for each
    axis.

    (constant,) or int is a shortcut for before = after = constant for
    all axes.

    Default is 0.
end_values : sequence or int, optional
    Used in 'linear_ramp'.  The values used for the ending value of the
    linear_ramp and that will form the edge of the padded array.

    ((before_1, after_1), ... (before_N, after_N)) unique end values
    for each axis.

    ((before, after),) yields same before and after end values for each
    axis.

    (constant,) or int is a shortcut for before = after = end value for
    all axes.

    Default is 0.
reflect_type : {'even', 'odd'}, optional
    Used in 'reflect', and 'symmetric'.  The 'even' style is the
    default with an unaltered reflection around the edge value.  For
    the 'odd' style, the extented part of the array is created by
    subtracting the reflected values from two times the edge value.

Returns
-------
pad : ndarray
    Padded array of rank equal to `array` with shape increased
    according to `pad_width`.

Notes
-----
.. versionadded:: 1.7.0

For an array with rank greater than 1, some of the padding of later
axes is calculated from padding of previous axes.  This is easiest to
think about with a rank 2 array where the corners of the padded array
are calculated by using padded values from the first axis.

The padding function, if used, should return a rank 1 array equal in
length to the vector argument with padded values replaced. It has the
following signature::

    padding_func(vector, iaxis_pad_width, iaxis, **kwargs)

where

    vector : ndarray
        A rank 1 array already padded with zeros.  Padded values are
        vector[:pad_tuple[0]] and vector[-pad_tuple[1]:].
    iaxis_pad_width : tuple
        A 2-tuple of ints, iaxis_pad_width[0] represents the number of
        values padded at the beginning of vector where
        iaxis_pad_width[1] represents the number of values padded at
        the end of vector.
    iaxis : int
        The axis currently being calculated.
    kwargs : misc
        Any keyword arguments the function requires.

Examples
--------
>>> a = [1, 2, 3, 4, 5]
>>> np.lib.pad(a, (2,3), 'constant', constant_values=(4, 6))
array([4, 4, 1, 2, 3, 4, 5, 6, 6, 6])

>>> np.lib.pad(a, (2, 3), 'edge')
array([1, 1, 1, 2, 3, 4, 5, 5, 5, 5])

>>> np.lib.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))
array([ 5,  3,  1,  2,  3,  4,  5,  2, -1, -4])

>>> np.lib.pad(a, (2,), 'maximum')
array([5, 5, 1, 2, 3, 4, 5, 5, 5])

>>> np.lib.pad(a, (2,), 'mean')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])

>>> np.lib.pad(a, (2,), 'median')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])

>>> a = [[1, 2], [3, 4]]
>>> np.lib.pad(a, ((3, 2), (2, 3)), 'minimum')
array([[1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [3, 3, 3, 4, 3, 3, 3],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1]])

>>> a = [1, 2, 3, 4, 5]
>>> np.lib.pad(a, (2, 3), 'reflect')
array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])

>>> np.lib.pad(a, (2, 3), 'reflect', reflect_type='odd')
array([-1,  0,  1,  2,  3,  4,  5,  6,  7,  8])

>>> np.lib.pad(a, (2, 3), 'symmetric')
array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])

>>> np.lib.pad(a, (2, 3), 'symmetric', reflect_type='odd')
array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])

>>> np.lib.pad(a, (2, 3), 'wrap')
array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])

>>> def padwithtens(vector, pad_width, iaxis, kwargs):
...     vector[:pad_width[0]] = 10
...     vector[-pad_width[1]:] = 10
...     return vector

>>> a = np.arange(6)
>>> a = a.reshape((2, 3))

>>> np.lib.pad(a, 2, padwithtens)
array([[10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10,  0,  1,  2, 10, 10],
       [10, 10,  3,  4,  5, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10]])
a = np.ones((10,10))
b = np.pad (a , pad_width = 1,mode ='constant',constant_values =2)
print (b)
[[ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]
 [ 2.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  2.]
 [ 2.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  2.]
 [ 2.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  2.]
 [ 2.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  2.]
 [ 2.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  2.]
 [ 2.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  2.]
 [ 2.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  2.]
 [ 2.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  2.]
 [ 2.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  2.]
 [ 2.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  2.]
 [ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]]

17. What is the result of the following expression? (★☆☆)

0 * np.nan
np.nan == np.nan
np.inf > np.nan
np.nan - np.nan
np.nan in set([np.nan])
0.3 == 3 * 0.1
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)
print (3*0.1)
nan
False
False
nan
False
0.30000000000000004

18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)

np.info(np.diag)
 diag(v, k=0)

Extract a diagonal or construct a diagonal array.

See the more detailed documentation for ``numpy.diagonal`` if you use this
function to extract a diagonal and wish to write to the resulting array;
whether it returns a copy or a view depends on what version of numpy you
are using.

Parameters
----------
v : array_like
    If `v` is a 2-D array, return a copy of its `k`-th diagonal.
    If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
    diagonal.
k : int, optional
    Diagonal in question. The default is 0. Use `k>0` for diagonals
    above the main diagonal, and `k<0` for diagonals below the main
    diagonal.

Returns
-------
out : ndarray
    The extracted diagonal or constructed diagonal array.

See Also
--------
diagonal : Return specified diagonals.
diagflat : Create a 2-D array with the flattened input as a diagonal.
trace : Sum along diagonals.
triu : Upper triangle of an array.
tril : Lower triangle of an array.

Examples
--------
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])

>>> np.diag(np.diag(x))
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])
a = np.diag([1,2,3,4],k=-1)
print (a)
[[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 (★☆☆)

a = np.ones((8,8),dtype = int)
a [::2,::2] = 0
a [1::2,1::2] = 0
print (a)
[[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]]
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?

print(np.unravel_index(100,(6,7,8)))
(1, 5, 4)
np.info(min)
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value

With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.

21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)

np.info(np.tile)
 tile(A, reps)

Construct an array by repeating A the number of times given by reps.

If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.

If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
or shape (1, 1, 3) for 3-D replication. If this is not the desired
behavior, promote `A` to d-dimensions manually before calling this
function.

If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it.
Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as
(1, 1, 2, 2).

Note : Although tile may be used for broadcasting, it is strongly
recommended to use numpy's broadcasting operations and functions.

Parameters
----------
A : array_like
    The input array.
reps : array_like
    The number of repetitions of `A` along each axis.

Returns
-------
c : ndarray
    The tiled output array.

See Also
--------
repeat : Repeat elements of an array.
broadcast_to : Broadcast an array to a new shape

Examples
--------
>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
>>> np.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
       [0, 1, 2, 0, 1, 2]])
>>> np.tile(a, (2, 1, 2))
array([[[0, 1, 2, 0, 1, 2]],
       [[0, 1, 2, 0, 1, 2]]])

>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1, 2, 1, 2],
       [3, 4, 3, 4]])
>>> np.tile(b, (2, 1))
array([[1, 2],
       [3, 4],
       [1, 2],
       [3, 4]])

>>> c = np.array([1,2,3,4])
>>> np.tile(c,(4,1))
array([[1, 2, 3, 4],
       [1, 2, 3, 4],
       [1, 2, 3, 4],
       [1, 2, 3, 4]])
b = np.tile( np.array([[0,1],[1,0]]), (4,4))
print (b)
[[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 (★☆☆)

#归一化找出最大值和最小值,然后把最大值和最小值分别用1和0表示,其他值则反映在0和1中间
a = np.random.random((5,5))
b = a
print (a)
print(b)
amin,amax = a.min(), a.max()
a = (a-amin)/(amax-amin)
print (a)


b = (b - np.mean (b)) / (np.std (b))
b==a

[[ 0.53137495  0.04086582  0.84109403  0.30730066  0.10427341]
 [ 0.59149722  0.60255845  0.36979078  0.33633652  0.93659627]
 [ 0.60845189  0.97575914  0.18083058  0.81637798  0.37766231]
 [ 0.37901819  0.58731292  0.18957854  0.49095575  0.69640366]
 [ 0.64511969  0.12767659  0.18747646  0.65510168  0.18463886]]
[[ 0.53137495  0.04086582  0.84109403  0.30730066  0.10427341]
 [ 0.59149722  0.60255845  0.36979078  0.33633652  0.93659627]
 [ 0.60845189  0.97575914  0.18083058  0.81637798  0.37766231]
 [ 0.37901819  0.58731292  0.18957854  0.49095575  0.69640366]
 [ 0.64511969  0.12767659  0.18747646  0.65510168  0.18463886]]
[[ 0.52466856  0.          0.85595671  0.28498956  0.06782334]
 [ 0.58897779  0.60080933  0.35183154  0.3160475   0.9581098 ]
 [ 0.60711319  1.          0.14971201  0.82951941  0.36025125]
 [ 0.36170156  0.58450208  0.15906918  0.48143453  0.70119   ]
 [ 0.64633456  0.09285633  0.15682072  0.6570117   0.1537855 ]]





array([[False, False, False, False, False],
       [False, False, False, False, False],
       [False, False, False, False, False],
       [False, False, False, False, False],
       [False, False, False, False, False]], dtype=bool)

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

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

dtype(obj, align=False, copy=False)

Create a data type object.

A numpy array is homogeneous, and contains elements described by a
dtype object. A dtype object can be constructed from different
combinations of fundamental numeric types.

Parameters
----------
obj
    Object to be converted to a data type object.
align : bool, optional
    Add padding to the fields to match what a C compiler would output
    for a similar C-struct. Can be ``True`` only if `obj` is a dictionary
    or a comma-separated string. If a struct dtype is being created,
    this also sets a sticky alignment flag ``isalignedstruct``.
copy : bool, optional
    Make a new copy of the data-type object. If ``False``, the result
    may just be a reference to a built-in data-type object.

See also
--------
result_type

Examples
--------
Using array-scalar type:

>>> np.dtype(np.int16)
dtype('int16')

Structured type, one field name 'f1', containing int16:

>>> np.dtype([('f1', np.int16)])
dtype([('f1', '<i2')])

Structured type, one field named 'f1', in itself containing a structured
type with one field:

>>> np.dtype([('f1', [('f1', np.int16)])])
dtype([('f1', [('f1', '<i2')])])

Structured type, two fields: the first field contains an unsigned int, the
second an int32:

>>> np.dtype([('f1', np.uint), ('f2', np.int32)])
dtype([('f1', '<u4'), ('f2', '<i4')])

Using array-protocol type strings:

>>> np.dtype([('a','f8'),('b','S10')])
dtype([('a', '<f8'), ('b', '|S10')])

Using comma-separated field formats.  The shape is (2,3):

>>> np.dtype("i4, (2,3)f8")
dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])

Using tuples.  ``int`` is a fixed type, 3 the field's shape.  ``void``
is a flexible type, here of size 10:

>>> np.dtype([('hello',(np.int,3)),('world',np.void,10)])
dtype([('hello', '<i4', 3), ('world', '|V10')])

Subdivide ``int16`` into 2 ``int8``'s, called x and y.  0 and 1 are
the offsets in bytes:

>>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
dtype(('<i2', [('x', '|i1'), ('y', '|i1')]))

Using dictionaries.  Two fields named 'gender' and 'age':

>>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
dtype([('gender', '|S1'), ('age', '|u1')])

Offsets in bytes, here 0 and 25:

>>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
dtype([('surname', '|S25'), ('age', '|u1')])


Methods:

  newbyteorder  --  newbyteorder(new_order='S')

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

a = np.random.random((5,3))
b = np.random.random((3,2))
c = np.dot(a,b)
print (c)
d = a@b
print (d)
[[ 0.09222333  0.33416668]
 [ 0.10808788  0.39195645]
 [ 0.15436294  0.60524329]
 [ 0.17113245  0.62218509]
 [ 0.11735987  0.43818705]]
[[ 0.09222333  0.33416668]
 [ 0.10808788  0.39195645]
 [ 0.15436294  0.60524329]
 [ 0.17113245  0.62218509]
 [ 0.11735987  0.43818705]]

25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)

a = np.arange(10)
print (a)
j =0
for i in a :
#     print (i)
    if ((3<i<=8)):
#         print(a)
        a[j] = a[j]*(-1)
    j = j+1
print (a)
[0 1 2 3 4 5 6 7 8 9]
[ 0  1  2  3 -4 -5 -6 -7 -8  9]
Z = np.arange(11)
a = (3 < Z) & (Z <= 8)
# print(Z>3) 
print(a)
print(Z[a])
# print(Z[5])
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)
[False False False False  True  True  True  True  True False False]
[4 5 6 7 8]
[ 0  1  2  3 -4 -5 -6 -7 -8  9 10]
a = np.array([1,2,3])
b = np.array([1,3,2])
print (a == b)
print (any(a == b))
print (all(a == b))
[ True False False]
True
False

猜你喜欢

转载自blog.csdn.net/weixin_43763724/article/details/88135009