abhishek-p/100-numpy-exercises - Jovian
Learn data science and machine learning by building real-world projects on Jovian

100 numpy exercises

Source: https://github.com/rougier/numpy-100

How to run this notebook

The recommended way to run this notebook is to click the "Run" button at the top of this page, and select "Run on Binder". This will run the notebook on mybinder.org, a free online service for running Jupyter notebooks.

How to get help

If you are stuck, you can ask for help on the community forum: https://jovian.ml/forum/t/100-numpy-exercises-hints-discussions-help/10561 . You can get help with errors, ask for hints, and share your solutions with others.

If you're new to Numpy, check out this notebook for a quick tutorial: https://jovian.ml/aakashns/python-numerical-computing-with-numpy

Saving your work

Remember to save a snapshot of your work from time to time using to your Jovian.ml account.

!pip install jovian --upgrade --quiet
import jovian
jovian.commit(project='100-numpy-exercises')
[jovian] Attempting to save notebook.. [jovian] Please enter your API key ( from https://jovian.ml/ ): API KEY: ········ [jovian] Creating a new project "abhishek-p/100-numpy-exercises" [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/abhishek-p/100-numpy-exercises

jovian.commit uploads the notebook to your Jovian.ml account, captures the Python environment and creates a shareable link for your notebook as shown above. You can use this link to share your work and let anyone (including you) run your notebooks and reproduce your work.

# Ucomment the next line if you need install numpy
# !pip install numpy --upgrade
1. Import the numpy package under the name np (★☆☆)
import numpy as np
2. Print the numpy version and the configuration (★☆☆)
np.version.version
'1.19.1'
3. Create a null vector of size 10 (★☆☆)
n=np.zeros(10)
4. How to find the memory size of any array (★☆☆)
n.size * n.itemsize
80
5. How to get the documentation of the numpy add function from the command line? (★☆☆)
help(np.add)
Help on ufunc object: add = class ufunc(builtins.object) | Functions that operate element by element on whole arrays. | | To see the documentation for a specific ufunc, use `info`. For | example, ``np.info(np.sin)``. Because ufuncs are written in C | (for speed) and linked into Python with NumPy's ufunc facility, | Python's help() function finds this page whenever help() is called | on a ufunc. | | A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`. | | Calling ufuncs: | =============== | | op(*x[, out], where=True, **kwargs) | Apply `op` to the arguments `*x` elementwise, broadcasting the arguments. | | The broadcasting rules are: | | * Dimensions of length 1 may be prepended to either array. | * Arrays may be repeated along dimensions of length 1. | | Parameters | ---------- | *x : array_like | Input arrays. | out : ndarray, None, or tuple of ndarray and None, optional | Alternate array object(s) in which to put the result; if provided, it | must have a shape that the inputs broadcast to. A tuple of arrays | (possible only as a keyword argument) must have length equal to the | number of outputs; use None for uninitialized outputs to be | allocated by the ufunc. | where : array_like, optional | This condition is broadcast over the input. At locations where the | condition is True, the `out` array will be set to the ufunc result. | Elsewhere, the `out` array will retain its original value. | Note that if an uninitialized `out` array is created via the default | ``out=None``, locations within it where the condition is False will | remain uninitialized. | **kwargs | For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`. | | Returns | ------- | r : ndarray or tuple of ndarray | `r` will have the shape that the arrays in `x` broadcast to; if `out` is | provided, it will be returned. If not, `r` will be allocated and | may contain uninitialized values. If the function has more than one | output, then the result will be a tuple of arrays. | | Methods defined here: | | __call__(self, /, *args, **kwargs) | Call self as a function. | | __repr__(self, /) | Return repr(self). | | __str__(self, /) | Return str(self). | | accumulate(...) | accumulate(array, axis=0, dtype=None, out=None) | | Accumulate the result of applying the operator to all elements. | | For a one-dimensional array, accumulate produces results equivalent to:: | | r = np.empty(len(A)) | t = op.identity # op = the ufunc being applied to A's elements | for i in range(len(A)): | t = op(t, A[i]) | r[i] = t | return r | | For example, add.accumulate() is equivalent to np.cumsum(). | | For a multi-dimensional array, accumulate is applied along only one | axis (axis zero by default; see Examples below) so repeated use is | necessary if one wants to accumulate over multiple axes. | | Parameters | ---------- | array : array_like | The array to act on. | axis : int, optional | The axis along which to apply the accumulation; default is zero. | dtype : data-type code, optional | The data-type used to represent the intermediate results. Defaults | to the data-type of the output array if such is provided, or the | the data-type of the input array if no output array is provided. | out : ndarray, None, or tuple of ndarray and None, optional | A location into which the result is stored. If not provided or None, | a freshly-allocated array is returned. For consistency with | ``ufunc.__call__``, if given as a keyword, this may be wrapped in a | 1-element tuple. | | .. versionchanged:: 1.13.0 | Tuples are allowed for keyword argument. | | Returns | ------- | r : ndarray | The accumulated values. If `out` was supplied, `r` is a reference to | `out`. | | Examples | -------- | 1-D array examples: | | >>> np.add.accumulate([2, 3, 5]) | array([ 2, 5, 10]) | >>> np.multiply.accumulate([2, 3, 5]) | array([ 2, 6, 30]) | | 2-D array examples: | | >>> I = np.eye(2) | >>> I | array([[1., 0.], | [0., 1.]]) | | Accumulate along axis 0 (rows), down columns: | | >>> np.add.accumulate(I, 0) | array([[1., 0.], | [1., 1.]]) | >>> np.add.accumulate(I) # no axis specified = axis zero | array([[1., 0.], | [1., 1.]]) | | Accumulate along axis 1 (columns), through rows: | | >>> np.add.accumulate(I, 1) | array([[1., 1.], | [0., 1.]]) | | at(...) | at(a, indices, b=None) | | Performs unbuffered in place operation on operand 'a' for elements | specified by 'indices'. For addition ufunc, this method is equivalent to | ``a[indices] += b``, except that results are accumulated for elements that | are indexed more than once. For example, ``a[[0,0]] += 1`` will only | increment the first element once because of buffering, whereas | ``add.at(a, [0,0], 1)`` will increment the first element twice. | | .. versionadded:: 1.8.0 | | Parameters | ---------- | a : array_like | The array to perform in place operation on. | indices : array_like or tuple | Array like index object or slice object for indexing into first | operand. If first operand has multiple dimensions, indices can be a | tuple of array like index objects or slice objects. | b : array_like | Second operand for ufuncs requiring two operands. Operand must be | broadcastable over first operand after indexing or slicing. | | Examples | -------- | Set items 0 and 1 to their negative values: | | >>> a = np.array([1, 2, 3, 4]) | >>> np.negative.at(a, [0, 1]) | >>> a | array([-1, -2, 3, 4]) | | Increment items 0 and 1, and increment item 2 twice: | | >>> a = np.array([1, 2, 3, 4]) | >>> np.add.at(a, [0, 1, 2, 2], 1) | >>> a | array([2, 3, 5, 4]) | | Add items 0 and 1 in first array to second array, | and store results in first array: | | >>> a = np.array([1, 2, 3, 4]) | >>> b = np.array([1, 2]) | >>> np.add.at(a, [0, 1], b) | >>> a | array([2, 4, 3, 4]) | | outer(...) | outer(A, B, **kwargs) | | Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`. | | Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of | ``op.outer(A, B)`` is an array of dimension M + N such that: | | .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] = | op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}]) | | For `A` and `B` one-dimensional, this is equivalent to:: | | r = empty(len(A),len(B)) | for i in range(len(A)): | for j in range(len(B)): | r[i,j] = op(A[i], B[j]) # op = ufunc in question | | Parameters | ---------- | A : array_like | First array | B : array_like | Second array | kwargs : any | Arguments to pass on to the ufunc. Typically `dtype` or `out`. | | Returns | ------- | r : ndarray | Output array | | See Also | -------- | numpy.outer : A less powerful version of ``np.multiply.outer`` | that `ravel`\ s all inputs to 1D. This exists | primarily for compatibility with old code. | | tensordot : ``np.tensordot(a, b, axes=((), ()))`` and | ``np.multiply.outer(a, b)`` behave same for all | dimensions of a and b. | | Examples | -------- | >>> np.multiply.outer([1, 2, 3], [4, 5, 6]) | array([[ 4, 5, 6], | [ 8, 10, 12], | [12, 15, 18]]) | | A multi-dimensional example: | | >>> A = np.array([[1, 2, 3], [4, 5, 6]]) | >>> A.shape | (2, 3) | >>> B = np.array([[1, 2, 3, 4]]) | >>> B.shape | (1, 4) | >>> C = np.multiply.outer(A, B) | >>> C.shape; C | (2, 3, 1, 4) | array([[[[ 1, 2, 3, 4]], | [[ 2, 4, 6, 8]], | [[ 3, 6, 9, 12]]], | [[[ 4, 8, 12, 16]], | [[ 5, 10, 15, 20]], | [[ 6, 12, 18, 24]]]]) | | reduce(...) | reduce(a, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True) | | Reduces `a`'s dimension by one, by applying ufunc along one axis. | | Let :math:`a.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then | :math:`ufunc.reduce(a, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` = | the result of iterating `j` over :math:`range(N_i)`, cumulatively applying | ufunc to each :math:`a[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`. | For a one-dimensional array, reduce produces results equivalent to: | :: | | r = op.identity # op = ufunc | for i in range(len(A)): | r = op(r, A[i]) | return r | | For example, add.reduce() is equivalent to sum(). | | Parameters | ---------- | a : array_like | The array to act on. | axis : None or int or tuple of ints, optional | Axis or axes along which a reduction is performed. | The default (`axis` = 0) is perform a reduction over the first | dimension of the input array. `axis` may be negative, in | which case it counts from the last to the first axis. | | .. versionadded:: 1.7.0 | | If this is None, a reduction is performed over all the axes. | If this is a tuple of ints, a reduction is performed on multiple | axes, instead of a single axis or all the axes as before. | | For operations which are either not commutative or not associative, | doing a reduction over multiple axes is not well-defined. The | ufuncs do not currently raise an exception in this case, but will | likely do so in the future. | dtype : data-type code, optional | The type used to represent the intermediate results. Defaults | to the data-type of the output array if this is provided, or | the data-type of the input array if no output array is provided. | out : ndarray, None, or tuple of ndarray and None, optional | A location into which the result is stored. If not provided or None, | a freshly-allocated array is returned. For consistency with | ``ufunc.__call__``, if given as a keyword, this may be wrapped in a | 1-element tuple. | | .. versionchanged:: 1.13.0 | Tuples are allowed for keyword argument. | keepdims : bool, optional | If this is set to True, the axes which are reduced are left | in the result as dimensions with size one. With this option, | the result will broadcast correctly against the original `arr`. | | .. versionadded:: 1.7.0 | initial : scalar, optional | The value with which to start the reduction. | If the ufunc has no identity or the dtype is object, this defaults | to None - otherwise it defaults to ufunc.identity. | If ``None`` is given, the first element of the reduction is used, | and an error is thrown if the reduction is empty. | | .. versionadded:: 1.15.0 | | where : array_like of bool, optional | A boolean array which is broadcasted to match the dimensions | of `a`, and selects elements to include in the reduction. Note | that for ufuncs like ``minimum`` that do not have an identity | defined, one has to pass in also ``initial``. | | .. versionadded:: 1.17.0 | | Returns | ------- | r : ndarray | The reduced array. If `out` was supplied, `r` is a reference to it. | | Examples | -------- | >>> np.multiply.reduce([2,3,5]) | 30 | | A multi-dimensional array example: | | >>> X = np.arange(8).reshape((2,2,2)) | >>> X | array([[[0, 1], | [2, 3]], | [[4, 5], | [6, 7]]]) | >>> np.add.reduce(X, 0) | array([[ 4, 6], | [ 8, 10]]) | >>> np.add.reduce(X) # confirm: default axis value is 0 | array([[ 4, 6], | [ 8, 10]]) | >>> np.add.reduce(X, 1) | array([[ 2, 4], | [10, 12]]) | >>> np.add.reduce(X, 2) | array([[ 1, 5], | [ 9, 13]]) | | You can use the ``initial`` keyword argument to initialize the reduction | with a different value, and ``where`` to select specific elements to include: | | >>> np.add.reduce([10], initial=5) | 15 | >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10) | array([14., 14.]) | >>> a = np.array([10., np.nan, 10]) | >>> np.add.reduce(a, where=~np.isnan(a)) | 20.0 | | Allows reductions of empty arrays where they would normally fail, i.e. | for ufuncs without an identity. | | >>> np.minimum.reduce([], initial=np.inf) | inf | >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False]) | array([ 1., 10.]) | >>> np.minimum.reduce([]) | Traceback (most recent call last): | ... | ValueError: zero-size array to reduction operation minimum which has no identity | | reduceat(...) | reduceat(a, indices, axis=0, dtype=None, out=None) | | Performs a (local) reduce with specified slices over a single axis. | | For i in ``range(len(indices))``, `reduceat` computes | ``ufunc.reduce(a[indices[i]:indices[i+1]])``, which becomes the i-th | generalized "row" parallel to `axis` in the final result (i.e., in a | 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if | `axis = 1`, it becomes the i-th column). There are three exceptions to this: | | * when ``i = len(indices) - 1`` (so for the last index), | ``indices[i+1] = a.shape[axis]``. | * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is | simply ``a[indices[i]]``. | * if ``indices[i] >= len(a)`` or ``indices[i] < 0``, an error is raised. | | The shape of the output depends on the size of `indices`, and may be | larger than `a` (this happens if ``len(indices) > a.shape[axis]``). | | Parameters | ---------- | a : array_like | The array to act on. | indices : array_like | Paired indices, comma separated (not colon), specifying slices to | reduce. | axis : int, optional | The axis along which to apply the reduceat. | dtype : data-type code, optional | The type used to represent the intermediate results. Defaults | to the data type of the output array if this is provided, or | the data type of the input array if no output array is provided. | out : ndarray, None, or tuple of ndarray and None, optional | A location into which the result is stored. If not provided or None, | a freshly-allocated array is returned. For consistency with | ``ufunc.__call__``, if given as a keyword, this may be wrapped in a | 1-element tuple. | | .. versionchanged:: 1.13.0 | Tuples are allowed for keyword argument. | | Returns | ------- | r : ndarray | The reduced values. If `out` was supplied, `r` is a reference to | `out`. | | Notes | ----- | A descriptive example: | | If `a` is 1-D, the function `ufunc.accumulate(a)` is the same as | ``ufunc.reduceat(a, indices)[::2]`` where `indices` is | ``range(len(array) - 1)`` with a zero placed | in every other element: | ``indices = zeros(2 * len(a) - 1)``, ``indices[1::2] = range(1, len(a))``. | | Don't be fooled by this attribute's name: `reduceat(a)` is not | necessarily smaller than `a`. | | Examples | -------- | To take the running sum of four successive values: | | >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2] | array([ 6, 10, 14, 18]) | | A 2-D example: | | >>> x = np.linspace(0, 15, 16).reshape(4,4) | >>> x | array([[ 0., 1., 2., 3.], | [ 4., 5., 6., 7.], | [ 8., 9., 10., 11.], | [12., 13., 14., 15.]]) | | :: | | # reduce such that the result has the following five rows: | # [row1 + row2 + row3] | # [row4] | # [row2] | # [row3] | # [row1 + row2 + row3 + row4] | | >>> np.add.reduceat(x, [0, 3, 1, 2, 0]) | array([[12., 15., 18., 21.], | [12., 13., 14., 15.], | [ 4., 5., 6., 7.], | [ 8., 9., 10., 11.], | [24., 28., 32., 36.]]) | | :: | | # reduce such that result has the following two columns: | # [col1 * col2 * col3, col4] | | >>> np.multiply.reduceat(x, [0, 3], 1) | array([[ 0., 3.], | [ 120., 7.], | [ 720., 11.], | [2184., 15.]]) | | ---------------------------------------------------------------------- | Data descriptors defined here: | | identity | The identity value. | | Data attribute containing the identity element for the ufunc, if it has one. | If it does not, the attribute value is None. | | Examples | -------- | >>> np.add.identity | 0 | >>> np.multiply.identity | 1 | >>> np.power.identity | 1 | >>> print(np.exp.identity) | None | | nargs | The number of arguments. | | Data attribute containing the number of arguments the ufunc takes, including | optional ones. | | Notes | ----- | Typically this value will be one more than what you might expect because all | ufuncs take the optional "out" argument. | | Examples | -------- | >>> np.add.nargs | 3 | >>> np.multiply.nargs | 3 | >>> np.power.nargs | 3 | >>> np.exp.nargs | 2 | | nin | The number of inputs. | | Data attribute containing the number of arguments the ufunc treats as input. | | Examples | -------- | >>> np.add.nin | 2 | >>> np.multiply.nin | 2 | >>> np.power.nin | 2 | >>> np.exp.nin | 1 | | nout | The number of outputs. | | Data attribute containing the number of arguments the ufunc treats as output. | | Notes | ----- | Since all ufuncs can take output arguments, this will always be (at least) 1. | | Examples | -------- | >>> np.add.nout | 1 | >>> np.multiply.nout | 1 | >>> np.power.nout | 1 | >>> np.exp.nout | 1 | | ntypes | The number of types. | | The number of numerical NumPy types - of which there are 18 total - on which | the ufunc can operate. | | See Also | -------- | numpy.ufunc.types | | Examples | -------- | >>> np.add.ntypes | 18 | >>> np.multiply.ntypes | 18 | >>> np.power.ntypes | 17 | >>> np.exp.ntypes | 7 | >>> np.remainder.ntypes | 14 | | signature | Definition of the core elements a generalized ufunc operates on. | | The signature determines how the dimensions of each input/output array | are split into core and loop dimensions: | | 1. Each dimension in the signature is matched to a dimension of the | corresponding passed-in array, starting from the end of the shape tuple. | 2. Core dimensions assigned to the same label in the signature must have | exactly matching sizes, no broadcasting is performed. | 3. The core dimensions are removed from all inputs and the remaining | dimensions are broadcast together, defining the loop dimensions. | | Notes | ----- | Generalized ufuncs are used internally in many linalg functions, and in | the testing suite; the examples below are taken from these. | For ufuncs that operate on scalars, the signature is None, which is | equivalent to '()' for every argument. | | Examples | -------- | >>> np.core.umath_tests.matrix_multiply.signature | '(m,n),(n,p)->(m,p)' | >>> np.linalg._umath_linalg.det.signature | '(m,m)->()' | >>> np.add.signature is None | True # equivalent to '(),()->()' | | types | Returns a list with types grouped input->output. | | Data attribute listing the data-type "Domain-Range" groupings the ufunc can | deliver. The data-types are given using the character codes. | | See Also | -------- | numpy.ufunc.ntypes | | Examples | -------- | >>> np.add.types | ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', | 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', | 'GG->G', 'OO->O'] | | >>> np.multiply.types | ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', | 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', | 'GG->G', 'OO->O'] | | >>> np.power.types | ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', | 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', | 'OO->O'] | | >>> np.exp.types | ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O'] | | >>> np.remainder.types | ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', | 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O']
6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)
n=np.zeros(10);
n[4]=1;
n
array([0., 0., 0., 0., 1., 0., 0., 0., 0., 0.])
7. Create a vector with values ranging from 10 to 49 (★☆☆)
np.arange(10,49)
array([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])
8. Reverse a vector (first element becomes last) (★☆☆)
n=np.array([1,2,3,4,5,6,7])
n[::-1]
array([7, 6, 5, 4, 3, 2, 1])
9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)
(np.arange(0,9)).reshape((3,3))
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
n=np.array([1,2,0,0,4,0] )
n.nonzero()
(array([0, 1, 4]),)

Save your progress by commiting your work to Jovian

import jovian
jovian.commit(project='numpy-100-exercises')
[jovian] Attempting to save notebook.. [jovian] Creating a new project "abhishek-p/numpy-100-exercises" [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/abhishek-p/numpy-100-exercises
11. Create a 3x3 identity matrix (★☆☆)
np.eye(3)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
12. Create a 3x3x3 array with random values (★☆☆)
np.random.rand(3,3,3)
array([[[0.36840257, 0.31150686, 0.9276335 ],
        [0.96526821, 0.79289589, 0.73614142],
        [0.44406169, 0.14994376, 0.35280784]],

       [[0.66975419, 0.78242702, 0.0214157 ],
        [0.84521953, 0.77665423, 0.37977462],
        [0.21262113, 0.43577485, 0.51677004]],

       [[0.96556914, 0.00694206, 0.14305224],
        [0.39907871, 0.7387387 , 0.30795233],
        [0.00707716, 0.00466449, 0.05923293]]])
13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)
k=np.random.rand(10,10)
k
array([[0.14931387, 0.82058391, 0.459991  , 0.80764018, 0.14690962,
        0.77881274, 0.16828098, 0.55087478, 0.78414573, 0.75907851],
       [0.69101799, 0.12986329, 0.0176528 , 0.97222764, 0.33081084,
        0.14053793, 0.03681302, 0.53233792, 0.63126339, 0.88183518],
       [0.42468815, 0.99484619, 0.49635862, 0.65537804, 0.10672969,
        0.24547634, 0.37691684, 0.54243933, 0.09585046, 0.48858151],
       [0.16555427, 0.84382699, 0.89172473, 0.90645   , 0.34322969,
        0.98014639, 0.62552626, 0.07639031, 0.02330048, 0.83833606],
       [0.30588022, 0.6526263 , 0.80756445, 0.67713463, 0.51845192,
        0.79346221, 0.07624766, 0.18257856, 0.86277786, 0.98897517],
       [0.6990044 , 0.89006764, 0.63992975, 0.02744584, 0.42320314,
        0.51255777, 0.79736583, 0.06600319, 0.23239045, 0.86973627],
       [0.39103921, 0.10003976, 0.34530513, 0.29638479, 0.477705  ,
        0.57439124, 0.02015245, 0.75153273, 0.69666493, 0.73714948],
       [0.91423693, 0.31753242, 0.18279211, 0.28677912, 0.28272688,
        0.72359714, 0.96909524, 0.77239468, 0.04531612, 0.81346817],
       [0.94797097, 0.97468478, 0.04996311, 0.40947557, 0.63364666,
        0.96870186, 0.46382388, 0.7063356 , 0.38120641, 0.00247733],
       [0.23027473, 0.79331469, 0.74775653, 0.61750354, 0.17973603,
        0.77911122, 0.39385813, 0.57663947, 0.98574761, 0.84971466]])
print('max',np.max(k),'min',np.min(k))
max 0.994846188879808 min 0.0024773341094630474
14. Create a random vector of size 30 and find the mean value (★☆☆)
k=np.random.rand(30)

np.mean(k)
0.44171407587126876
k.sum()/30
0.44171407587126876
15. Create a 2d array with 1 on the border and 0 inside (★☆☆)
 
16. How to add a border (filled with 0's) around an existing array? (★☆☆)
 
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
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
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-1-5ca840bfb533> in <module> ----> 1 0 * np.nan 2 np.nan == np.nan 3 np.inf > np.nan 4 np.nan - np.nan 5 np.nan in set([np.nan]) NameError: name 'np' is not defined
18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)
 
19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)
 
20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?
 

Save your progress by commiting your work to Jovian

import jovian
jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Updating notebook "aakashns/numpy-100-exercises" on https://jovian.ml/ [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/aakashns/numpy-100-exercises
21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)
 
22. Normalize a 5x5 random matrix (★☆☆)
 
23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)
 
24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)
 
25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)
 
26. What is the output of the following script? (★☆☆)
# Author: Jake VanderPlas

print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
 
27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)
Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z
 
28. What are the result of the following expressions?
np.array(0) / np.array(0)
np.array(0) // np.array(0)
np.array([np.nan]).astype(int).astype(float)
 
29. How to round away from zero a float array ? (★☆☆)
 
30. How to find common values between two arrays? (★☆☆)
 

Save your progress by commiting your work to Jovian

import jovian
jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Updating notebook "aakashns/numpy-100-exercises" on https://jovian.ml/ [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/aakashns/numpy-100-exercises
31. How to ignore all numpy warnings (not recommended)? (★☆☆)
 
32. Is the following expressions true? (★☆☆)
np.sqrt(-1) == np.emath.sqrt(-1)
 
33. How to get the dates of yesterday, today and tomorrow? (★☆☆)
 
34. How to get all the dates corresponding to the month of July 2016? (★★☆)
 
35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)
 
36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)
 
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 (★☆☆)
 
39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)
 
40. Create a random vector of size 10 and sort it (★★☆)
 

Save your progress by commiting your work to Jovian

import jovian
jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Updating notebook "aakashns/numpy-100-exercises" on https://jovian.ml/ [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/aakashns/numpy-100-exercises
41. How to sum a small array faster than np.sum? (★★☆)
 
42. Consider two random array A and B, check if they are equal (★★☆)
 
43. Make an array immutable (read-only) (★★☆)
 
44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
 
45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)
 
46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)
 
47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))
 
48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)
 
49. How to print all the values of an array? (★★☆)
 
50. How to find the closest value (to a given scalar) in a vector? (★★☆)
 

Save and commit your work.

import jovian
jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Updating notebook "aakashns/numpy-100-exercises" on https://jovian.ml/ [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/aakashns/numpy-100-exercises
51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)
 
52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)
 
53. How to convert a float (32 bits) array into an integer (32 bits) in place?
 
54. How to read the following file? (★★☆)
1, 2, 3, 4, 5
6,  ,  , 7, 8
 ,  , 9,10,11
 
55. What is the equivalent of enumerate for numpy arrays? (★★☆)
 
56. Generate a generic 2D Gaussian-like array (★★☆)
 
57. How to randomly place p elements in a 2D array? (★★☆)
 
58. Subtract the mean of each row of a matrix (★★☆)
 
59. How to sort an array by the nth column? (★★☆)
 
60. How to tell if a given 2D array has null columns? (★★☆)
 

Save and commit your work.

import jovian
jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Updating notebook "aakashns/numpy-100-exercises" on https://jovian.ml/ [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/aakashns/numpy-100-exercises
61. Find the nearest value from a given value in an array (★★☆)
 
62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)
 
63. Create an array class that has a name attribute (★★☆)
 
64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)
 
65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)
 
66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★)
 
67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)
 
68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★)
 
69. How to get the diagonal of a dot product? (★★★)
 
70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)
 
 

Save and commit your work

import jovian
jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Updating notebook "aakashns/numpy-100-exercises" on https://jovian.ml/ [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/aakashns/numpy-100-exercises
71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)
 
72. How to swap two rows of an array? (★★★)
 
73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)
 
74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)
 
75. How to compute averages using a sliding window over an array? (★★★)
 
76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (★★★)
 
77. How to negate a boolean, or to change the sign of a float inplace? (★★★)
 
78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])? (★★★)
 
79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (★★★)
 
80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a fill value when necessary) (★★★)
 

Save and commit your work.

import jovian
jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Updating notebook "aakashns/numpy-100-exercises" on https://jovian.ml/ [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/aakashns/numpy-100-exercises
81. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]? (★★★)
 
82. Compute a matrix rank (★★★)
 
83. How to find the most frequent value in an array?
 
84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)
 
85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)
 
86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★)
 
87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)
 
88. How to implement the Game of Life using numpy arrays? (★★★)
 
89. How to get the n largest values of an array (★★★)
 
90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)
 

Save and commit your work

import jovian
jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Updating notebook "aakashns/numpy-100-exercises" on https://jovian.ml/ [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/aakashns/numpy-100-exercises
91. How to create a record array from a regular array? (★★★)
 
92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)
 
93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (★★★)
 
94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)
 
95. Convert a vector of ints into a matrix binary representation (★★★)
 
96. Given a two dimensional array, how to extract unique rows? (★★★)
 
97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)
 
98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?
 
99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (★★★)
 
100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means). (★★★)
 

Save and commit your work

import jovian
jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Updating notebook "aakashns/numpy-100-exercises" on https://jovian.ml/ [jovian] Uploading notebook.. [jovian] Capturing environment.. [jovian] Committed successfully! https://jovian.ml/aakashns/numpy-100-exercises

Congratulations on completing the 100 exercises, you're now an expert on Numpy!!

What to do next?