numpy-100/100 Numpy exercises.rst

1183 lines
29 KiB
ReStructuredText
Raw Normal View History

2016-03-08 21:02:50 +01:00
100 numpy exercises
2016-07-15 15:06:49 +02:00
===================
2014-05-27 06:18:00 +02:00
2016-07-15 15:06:49 +02:00
This is a collection of exercises that have been collected in the numpy mailing
list, on stack overflow and in the numpy documentation. I've also created some
to reach the 100 limit. The goal of this collection is to offer a quick
reference for both old and new users but also to provide a set of exercices for
those who teach.
2014-05-27 06:18:00 +02:00
2016-07-15 15:06:49 +02:00
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
2014-06-22 17:01:01 +02:00
2016-03-08 21:02:50 +01:00
#. Import the numpy package under the name ``np`` (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
import numpy as np
2016-03-08 21:02:50 +01:00
#. Print the numpy version and the configuration (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2015-08-18 23:54:55 +02:00
print(np.__version__)
2016-03-09 09:43:04 +01:00
np.show_config()
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create a null vector of size 10 (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.zeros(10)
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-29 21:48:26 +02:00
#. How to find the memory size of any array (★☆☆)
.. code-block:: python
Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itesize))
2016-07-14 18:55:31 +02:00
#. How to get the documentation of the numpy add function from the command line? (★☆☆)
.. code-block:: bash
2014-05-27 06:18:00 +02:00
python -c "import numpy; numpy.info(numpy.add)"
2016-03-08 21:02:50 +01:00
#. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.zeros(10)
Z[4] = 1
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create a vector with values ranging from 10 to 49 (★☆☆)
2014-05-29 21:48:26 +02:00
.. code-block:: python
Z = np.arange(10,50)
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Reverse a vector (first element becomes last) (★☆☆)
.. code-block:: python
Z = np.arange(50)
Z = Z[::-1]
2016-03-08 21:02:50 +01:00
#. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.arange(9).reshape(3,3)
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-29 21:48:26 +02:00
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
nz = np.nonzero([1,2,0,0,4,0])
2015-08-18 23:54:55 +02:00
print(nz)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create a 3x3 identity matrix (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.eye(3)
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-29 21:48:26 +02:00
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create a 3x3x3 array with random values (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.random.random((3,3,3))
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-29 21:48:26 +02:00
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)
2014-05-27 06:18:00 +02:00
2015-08-16 21:01:30 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create a random vector of size 30 and find the mean value (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.random.random(30)
m = Z.mean()
print(m)
2016-07-15 00:47:38 +02:00
#. Create a 2d array with 1 on the border and 0 inside (★☆☆)
2016-03-08 21:02:50 +01:00
.. code-block:: python
Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
2016-07-15 00:47:38 +02:00
#. How to add a border (filled with 0's) around an existing array ? (★☆☆)
.. code-block:: python
Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
2016-07-14 18:55:31 +02:00
#. What is the result of the following expression? (★☆☆)
2016-03-08 21:02:50 +01:00
.. code-block:: python
0 * np.nan
np.nan == np.nan
np.inf > np.nan
np.nan - np.nan
0.3 == 3 * 0.1
#. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.diag(1+np.arange(4),k=-1)
print(Z)
2016-03-08 21:02:50 +01:00
#. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
2014-05-29 21:48:26 +02:00
2016-07-14 18:55:31 +02:00
#. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?
2016-03-08 21:02:50 +01:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
print(np.unravel_index(100,(6,7,8)))
#. Create a checkerboard 8x8 matrix using the tile function (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-29 21:48:26 +02:00
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Normalize a 5x5 random matrix (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.random.random((5,5))
2015-08-18 23:54:55 +02:00
Zmax, Zmin = Z.max(), Z.min()
2014-05-27 06:18:00 +02:00
Z = (Z - Zmin)/(Zmax - Zmin)
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-27 06:18:00 +02:00
2016-07-14 18:55:31 +02:00
#. Create a custom dtype that describes a color as four unisgned bytes (RGBA) (★☆☆)
.. code-block:: python
color = np.dtype([("r", np.ubyte, 1),
("g", np.ubyte, 1),
("b", np.ubyte, 1),
("a", np.ubyte, 1)])
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-27 06:18:00 +02:00
2016-07-14 18:55:31 +02:00
#. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)
2016-03-09 10:34:08 +01:00
.. code-block:: python
# Author: Evgeni Burovski
Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1
2016-07-14 18:55:31 +02:00
#. What is the output of the following script? (★☆☆)
.. code-block:: python
# Author: Jake VanderPlas
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
#. Consider an integer vector Z, which of these expressions are legal? (★☆☆)
.. code-block:: python
Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z
#. What are the result of the following expressions?
.. code-block:: python
np.array(0) / np.array(0)
np.array(0) // np.array(0)
np.array([np.nan]).astype(int).astype(float)
2016-07-14 18:55:31 +02:00
#. How to round away from zero a float array ? (★☆☆)
.. code-block:: python
# Author: Charles R Harris
Z = np.random.uniform(-10,+10,10)
print (np.trunc(Z + np.copysign(0.5, Z)))
2016-07-15 00:59:29 +02:00
#. How to find common values between two arrays? (★☆☆)
.. code-block:: python
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))
2016-07-15 03:21:23 +02:00
#. How to ignore all numpy warnings (not recommended)? (★☆☆)
.. code-block:: python
# Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1)/0
# Back to sanity
np.seterr(**defaults)
#. Is the following expressions true? (★☆☆)
.. code-block:: python
2016-07-15 01:28:02 +02:00
np.sqrt(-1) == np.emath.sqrt(-1)
2016-07-14 18:55:31 +02:00
2016-07-15 03:21:23 +02:00
#. How to get the dates of yesterday, today and tomorrow? (★☆☆)
2016-07-15 02:58:32 +02:00
.. code-block:: python
2016-07-15 03:21:23 +02:00
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
2016-07-15 02:58:32 +02:00
#. How to get all the dates corresponding to the month of July 2016? (★★☆)
.. code-block:: python
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)
2016-07-15 02:36:32 +02:00
#. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)
.. code-block:: python
A = np.ones(3)*1
B = np.ones(3)*2
C = np.ones(3)*3
np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)
2016-07-14 18:55:31 +02:00
#. Extract the integer part of a random array using 5 different methods (★★☆)
.. code-block:: python
Z = np.random.uniform(0,10,10)
print (Z - Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
Z = np.zeros((5,5))
Z += np.arange(5)
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Consider a generator function that generates 10 integers and use it to build an
array (★☆☆)
.. code-block:: python
def generate():
for x in xrange(10):
yield x
Z = np.fromiter(generate(),dtype=float,count=-1)
print(Z)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
Z = np.linspace(0,1,12,endpoint=True)[1:-1]
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-27 06:18:00 +02:00
#. Create a random vector of size 10 and sort it (★★☆)
2014-05-29 21:48:26 +02:00
.. code-block:: python
Z = np.random.random(10)
2014-05-27 06:18:00 +02:00
Z.sort()
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-27 06:18:00 +02:00
2016-07-14 18:55:31 +02:00
#. How to sum a small array faster than np.sum? (★★☆)
.. code-block:: python
# Author: Evgeni Burovski
Z = np.arange(10)
np.add.reduce(Z)
2016-03-08 21:02:50 +01:00
#. Consider two random array A anb B, check if they are equal (★★☆)
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
2014-05-27 06:18:00 +02:00
equal = np.allclose(A,B)
2015-08-18 23:54:55 +02:00
print(equal)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Make an array immutable (read-only) (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.zeros(10)
Z.flags.writeable = False
2014-05-29 21:48:26 +02:00
Z[0] = 1
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. Consider a random 10x2 matrix representing cartesian coordinates, convert
2016-03-08 21:02:50 +01:00
them to polar coordinates (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
Z = np.random.random((10,2))
2014-05-27 06:18:00 +02:00
X,Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2+Y**2)
T = np.arctan2(Y,X)
2015-08-18 23:54:55 +02:00
print(R)
print(T)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create random vector of size 10 and replace the maximum value by 0 (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
Z = np.random.random(10)
2014-05-27 06:18:00 +02:00
Z[Z.argmax()] = 0
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. Create a structured array with ``x`` and ``y`` coordinates covering the
2016-03-08 21:02:50 +01:00
[0,1]x[0,1] area (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.zeros((10,10), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,10),
np.linspace(0,1,10))
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-29 21:48:26 +02:00
2014-05-27 06:18:00 +02:00
#. Given two arrays, X and Y, construct the Cauchy matrix C (Cij = 1/(xi - yj))
.. code-block:: python
# Author: Evgeni Burovski
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
2016-03-08 21:02:50 +01:00
#. Print the minimum and maximum representable value for each numpy scalar type (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
for dtype in [np.int8, np.int32, np.int64]:
2015-08-18 23:54:55 +02:00
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
2014-05-27 06:18:00 +02:00
for dtype in [np.float32, np.float64]:
2015-08-18 23:54:55 +02:00
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps)
2014-05-27 06:18:00 +02:00
2016-07-14 18:55:31 +02:00
#. How to print all the values of an array? (★★☆)
2016-03-08 21:02:50 +01:00
.. code-block:: python
np.set_printoptions(threshold=np.nan)
Z = np.zeros((25,25))
print(Z)
2016-07-14 18:55:31 +02:00
#. How to find the closest value (to a given scalar) in an array? (★★☆)
2016-03-08 21:02:50 +01:00
.. code-block:: python
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print(Z[index])
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.zeros(10, [ ('position', [ ('x', float, 1),
('y', float, 1)]),
('color', [ ('r', float, 1),
('g', float, 1),
('b', float, 1)])])
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. Consider a random vector with shape (100,2) representing coordinates, find
2016-03-08 21:02:50 +01:00
point by point distances (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0]), np.atleast_2d(Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
2015-08-18 23:54:55 +02:00
print(D)
2014-05-27 06:18:00 +02:00
# Much faster with scipy
2014-05-29 21:48:26 +02:00
import scipy
2015-08-22 17:56:07 +02:00
# Thanks Gavin Heverly-Coulson (#issue 1)
import scipy.spatial
2014-05-27 06:18:00 +02:00
Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
2015-08-18 23:54:55 +02:00
print(D)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
2016-07-14 18:55:31 +02:00
#. How to convert a float (32 bits) array into an integer (32 bits) in place?
2016-03-08 21:02:50 +01:00
.. code-block:: python
Z = np.arange(10, dtype=np.int32)
Z = Z.astype(np.float32, copy=False)
2016-07-14 18:55:31 +02:00
#. How to read the following file? (★★☆)
.. code-block:: python
2016-07-14 18:55:31 +02:00
# File content:
# -------------
1,2,3,4,5
6,,,7,8
,,9,10,11
# -------------
Z = np.genfromtxt("missing.dat", delimiter=",")
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
2016-07-14 18:55:31 +02:00
#. What is the equivalent of `enumerate` for numpy arrays? (★★☆)
2016-03-08 21:02:50 +01:00
.. code-block:: python
Z = np.arange(9).reshape(3,3)
for index, value in np.ndenumerate(Z):
print(index, value)
for index in np.ndindex(Z.shape):
print(index, Z[index])
#. Generate a generic 2D Gaussian-like array (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
2014-05-27 06:18:00 +02:00
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
2015-08-18 23:54:55 +02:00
print(G)
2014-05-29 21:48:26 +02:00
2016-07-14 18:55:31 +02:00
#. How to randomly place p elements in a 2D array? (★★☆)
2016-03-08 21:02:50 +01:00
.. code-block:: python
2016-03-08 21:02:50 +01:00
# Author: Divakar
2016-03-08 21:02:50 +01:00
n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
2016-03-08 21:02:50 +01:00
#. Subtract the mean of each row of a matrix (★★☆)
.. code-block:: python
# Author: Warren Weckesser
X = np.random.rand(5, 10)
# Recent versions of numpy
Y = X - X.mean(axis=1, keepdims=True)
# Older versions of numpy
Y = X - X.mean(axis=1).reshape(-1, 1)
2016-07-14 18:55:31 +02:00
#. How to I sort an array by the nth column? (★★☆)
.. code-block:: python
# Author: Steve Tjoa
Z = np.random.randint(0,10,(3,3))
print(Z)
print(Z[Z[:,1].argsort()])
2014-05-27 06:18:00 +02:00
2016-07-14 18:55:31 +02:00
#. How to tell if a given 2D array has null columns? (★★☆)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
# Author: Warren Weckesser
2014-06-23 09:32:51 +02:00
Z = np.random.randint(0,3,(3,10))
2015-08-18 23:54:55 +02:00
print((~Z.any(axis=0)).any())
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Find the nearest value from a given value in an array (★★☆)
2014-05-27 06:18:00 +02:00
2015-08-16 21:01:30 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2015-08-16 21:01:30 +02:00
Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
2015-08-18 23:54:55 +02:00
print(m)
2014-05-27 06:18:00 +02:00
#. Considering two arrays with shape (1,3) and (3,1), how to compute their sum
using an iterator? (★★☆)
.. code-block:: python
A = np.arange(3).reshape(3,1)
B = np.arange(3).reshape(1,3)
it = np.nditer([A,B,None]):
for x,y,z in it: z[...] = x + y
C = it.operands[2]
2016-07-14 18:55:31 +02:00
#. Create an array class that has a `name` attribute (★★☆)
2014-05-27 06:18:00 +02:00
2016-07-14 18:55:31 +02:00
.. code-block:: python
class NamedArray(np.ndarray):
def __new__(cls, array, name="no name"):
obj = np.asarray(array).view(cls)
obj.name = name
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'name', "no name")
Z = NamedArray(np.arange(10), "range_10")
print (Z.name)
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. Consider a given vector, how to add 1 to each element indexed by a second
2016-07-14 18:55:31 +02:00
vector (be careful with repeated indices)? (★★★)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
# Author: Brett Olsen
Z = np.ones(10)
I = np.random.randint(0,len(Z),20)
Z += np.bincount(I, minlength=len(Z))
2015-08-18 23:54:55 +02:00
print(Z)
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. How to accumulate elements of a vector (X) to an array (F) based on an index
2016-07-14 18:55:31 +02:00
list (I)? (★★★)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
# Author: Alan G Isaac
X = [1,2,3,4,5,6]
I = [1,3,9,3,4,1]
F = np.bincount(I,X)
2015-08-18 23:54:55 +02:00
print(F)
2014-05-29 21:48:26 +02:00
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique
2016-03-08 21:02:50 +01:00
colors (★★★)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
# Author: Nadav Horesh
w,h = 16,16
I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
F = I[...,0]*256*256 + I[...,1]*256 +I[...,2]
n = len(np.unique(F))
2015-08-18 23:54:55 +02:00
print(np.unique(I))
2014-05-27 06:18:00 +02:00
2014-06-23 09:32:51 +02:00
#. Considering a four dimensions array, how to get sum over the last two axis
2016-07-14 18:55:31 +02:00
at once? (★★★)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
A = np.random.randint(0,10,(3,4,3,4))
sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
2015-08-18 23:54:55 +02:00
print(sum)
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. Considering a one-dimensional vector D, how to compute means of subsets of D
2016-07-14 18:55:31 +02:00
using a vector S of same size describing subset indices? (★★★)
2014-05-27 06:50:50 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:50:50 +02:00
2014-06-08 20:26:09 +02:00
# Author: Jaime Fernández del Río
2014-05-27 06:50:50 +02:00
D = np.random.uniform(0,1,100)
S = np.random.randint(0,10,100)
D_sums = np.bincount(S, weights=D)
D_counts = np.bincount(S)
D_means = D_sums / D_counts
2015-08-18 23:54:55 +02:00
print(D_means)
2014-05-27 06:50:50 +02:00
2016-07-14 18:55:31 +02:00
#. How to get the diagonal of a dot product? (★★★)
.. code-block:: python
# Author: Mathieu Blondel
# Slow version
np.diag(np.dot(A, B))
# Fast version
np.sum(A * B.T, axis=1)
# Faster version
np.einsum("ij,ji->i", A, B).
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3
2016-07-14 18:55:31 +02:00
consecutive zeros interleaved between each value? (★★★)
2014-06-23 09:32:51 +02:00
.. code-block:: python
# Author: Warren Weckesser
Z = np.array([1,2,3,4,5])
nz = 3
Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
Z0[::nz+1] = Z
2015-08-18 23:54:55 +02:00
print(Z0)
2014-06-23 09:32:51 +02:00
2015-08-16 19:55:47 +02:00
#. Consider an array of dimension (5,5,3), how to mulitply it by an array with
2016-07-14 18:55:31 +02:00
dimensions (5,5)? (★★★)
2014-06-23 09:32:51 +02:00
.. code-block:: python
A = np.ones((5,5,3))
B = 2*np.ones((5,5))
2015-08-18 23:54:55 +02:00
print(A * B[:,:,None])
2014-06-23 09:32:51 +02:00
2016-07-14 18:55:31 +02:00
#. How to swap two rows of an array? (★★★)
2014-06-23 09:32:51 +02:00
2015-08-16 21:01:30 +02:00
.. code-block:: python
2014-06-23 09:32:51 +02:00
2015-08-16 21:01:30 +02:00
# Author: Eelco Hoogendoorn
2014-06-23 09:32:51 +02:00
2015-08-16 21:01:30 +02:00
A = np.arange(25).reshape(5,5)
A[[0,1]] = A[[1,0]]
2015-08-18 23:54:55 +02:00
print(A)
2014-06-23 09:32:51 +02:00
2014-05-27 06:44:09 +02:00
2015-08-16 19:55:47 +02:00
#. Consider a set of 10 triplets describing 10 triangles (with shared
2016-03-08 21:02:50 +01:00
vertices), find the set of unique line segments composing all the triangles (★★★)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2014-06-08 20:26:09 +02:00
# Author: Nicolas P. Rougier
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
faces = np.random.randint(0,100,(10,3))
2014-05-27 06:18:00 +02:00
F = np.roll(faces.repeat(2,axis=1),-1,axis=1)
F = F.reshape(len(F)*3,2)
F = np.sort(F,axis=1)
G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )
G = np.unique(G)
2015-08-18 23:54:55 +02:00
print(G)
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. Given an array C that is a bincount, how to produce an array A such that
2016-07-14 18:55:31 +02:00
np.bincount(A) == C? (★★★)
2014-05-27 06:44:09 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:44:09 +02:00
2014-06-08 20:26:09 +02:00
# Author: Jaime Fernández del Río
2014-05-27 06:50:50 +02:00
2014-05-27 06:44:09 +02:00
C = np.bincount([1,1,2,3,4,4,6])
A = np.repeat(np.arange(len(C)), C)
2015-08-18 23:54:55 +02:00
print(A)
2014-05-27 06:44:09 +02:00
2016-07-14 18:55:31 +02:00
#. How to compute averages using a sliding window over an array? (★★★)
2014-05-29 21:58:17 +02:00
.. code-block:: python
# Author: Jaime Fernández del Río
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
Z = np.arange(20)
2015-08-18 23:54:55 +02:00
print(moving_average(Z, n=3))
2014-05-27 06:44:09 +02:00
#. 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
2016-03-08 21:02:50 +01:00
row should be (Z[-3],Z[-2],Z[-1]) (★★★)
2015-02-26 18:24:23 +01:00
.. code-block:: python
2015-02-26 18:24:23 +01:00
# Author: Joe Kington / Erik Rigtorp
from numpy.lib import stride_tricks
def rolling(a, window):
shape = (a.size - window + 1, window)
strides = (a.itemsize, a.itemsize)
return stride_tricks.as_strided(a, shape=shape, strides=strides)
Z = rolling(np.arange(10), 3)
print(Z)
2015-02-26 18:24:23 +01:00
2016-07-14 18:55:31 +02:00
#. How to negate a boolean, or to change the sign of a float inplace? (★★★)
2015-02-26 18:24:23 +01:00
2015-08-16 19:55:47 +02:00
.. code-block:: python
2015-02-26 18:24:23 +01:00
2015-08-16 19:55:47 +02:00
# Author: Nathaniel J. Smith
2015-02-26 18:24:23 +01:00
2015-08-16 19:55:47 +02:00
Z = np.random.randint(0,2,100)
np.logical_not(arr, out=arr)
2015-02-26 18:24:23 +01:00
2015-08-16 19:55:47 +02:00
Z = np.random.uniform(-1.0,1.0,100)
np.negative(arr, out=arr)
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to
2016-07-14 18:55:31 +02:00
compute distance from p to each line i (P0[i],P1[i])? (★★★)
.. code-block:: python
def distance(P0, P1, p):
2015-02-26 18:24:23 +01:00
T = P1 - P0
L = (T**2).sum(axis=1)
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
U = U.reshape(len(U),1)
D = P0 + U*T - p
return np.sqrt((D**2).sum(axis=1))
2014-07-20 11:53:29 +02:00
P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10,10,( 1,2))
2015-08-18 23:54:55 +02:00
print(distance(P0, P1, p))
2015-08-16 19:55:47 +02:00
#. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P,
2016-07-14 18:55:31 +02:00
how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (★★★)
.. code-block:: python
2015-08-22 09:19:50 +02:00
# Author: Italmassov Kuanysh
# based on distance function from previous question
P0 = np.random.uniform(-10, 10, (10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10, 10, (10,2))
print np.array([distance(P0,P1,p_i) for p_i in p])
2015-08-16 19:55:47 +02:00
#. Consider an arbitrary array, write a function that extract a subpart with a
2014-05-27 06:18:00 +02:00
fixed shape and centered on a given element (pad with a ``fill`` value when
2016-03-08 21:02:50 +01:00
necessary) (★★★)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code:: python
2014-05-27 06:18:00 +02:00
# Author: Nicolas Rougier
2014-05-29 21:48:26 +02:00
Z = np.random.randint(0,10,(10,10))
shape = (5,5)
2014-05-27 06:18:00 +02:00
fill = 0
2014-05-29 21:48:26 +02:00
position = (1,1)
2014-05-27 06:18:00 +02:00
R = np.ones(shape, dtype=Z.dtype)*fill
P = np.array(list(position)).astype(int)
Rs = np.array(list(R.shape)).astype(int)
Zs = np.array(list(Z.shape)).astype(int)
R_start = np.zeros((len(shape),)).astype(int)
R_stop = np.array(list(shape)).astype(int)
Z_start = (P-Rs//2)
Z_stop = (P+Rs//2)+Rs%2
R_start = (R_start - np.minimum(Z_start,0)).tolist()
Z_start = (np.maximum(Z_start,0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
R[r] = Z[z]
2015-08-18 23:54:55 +02:00
print(Z)
print(R)
2014-05-27 06:18:00 +02:00
2015-08-16 19:55:47 +02:00
#. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an
2016-07-14 18:55:31 +02:00
array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]? (★★★)
2014-05-27 21:47:22 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 21:47:22 +02:00
# Author: Stefan van der Walt
2014-05-27 21:47:22 +02:00
2014-05-29 21:48:26 +02:00
Z = np.arange(1,15,dtype=uint32)
R = stride_tricks.as_strided(Z,(11,4),(4,4))
2015-08-18 23:54:55 +02:00
print(R)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Compute a matrix rank (★★★)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
# Author: Stefan van der Walt
Z = np.random.uniform(0,1,(10,10))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
2014-05-27 06:18:00 +02:00
2016-07-14 18:55:31 +02:00
#. How to find the most frequent value in an array?
2016-03-08 21:02:50 +01:00
.. code-block:: python
Z = np.random.randint(0,10,50)
print(np.bincount(Z).argmax())
2016-03-08 21:02:50 +01:00
#. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)
2014-05-27 06:18:00 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 06:18:00 +02:00
2014-05-29 21:58:17 +02:00
# Author: Chris Barker
2014-05-27 06:18:00 +02:00
Z = np.random.randint(0,5,(10,10))
n = 3
i = 1 + (Z.shape[0]-3)
j = 1 + (Z.shape[1]-3)
C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)
2015-08-18 23:54:55 +02:00
print(C)
2014-05-27 06:18:00 +02:00
2016-03-08 21:02:50 +01:00
#. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)
2014-05-27 09:54:55 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 09:54:55 +02:00
2014-06-08 20:26:09 +02:00
# Author: Eric O. Lebigot
2014-05-27 09:54:55 +02:00
# Note: only works for 2d array and value setting using indices
class Symetric(np.ndarray):
def __setitem__(self, (i,j), value):
super(Symetric, self).__setitem__((i,j), value)
super(Symetric, self).__setitem__((j,i), value)
def symetric(Z):
return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)
2014-05-29 21:48:26 +02:00
S = symetric(np.random.randint(0,10,(5,5)))
2014-05-27 09:54:55 +02:00
S[2,3] = 42
2015-08-18 23:54:55 +02:00
print(S)
2014-05-27 09:54:55 +02:00
2015-08-16 19:55:47 +02:00
#. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1).
2016-07-14 18:55:31 +02:00
How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★)
2014-06-08 20:21:30 +02:00
.. code-block:: python
# Author: Stefan van der Walt
2014-06-08 20:21:30 +02:00
p, n = 10, 20
M = np.ones((p,n,n))
V = np.ones((p,n,1))
S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
2015-08-18 23:54:55 +02:00
print(S)
2014-06-08 20:21:30 +02:00
# It works, because:
2014-06-08 20:29:08 +02:00
# M is (p,n,n)
# V is (p,n,1)
2014-06-08 20:21:30 +02:00
# Thus, summing over the paired axes 0 and 0 (of M and V independently),
2014-06-08 20:29:08 +02:00
# and 2 and 1, to remain with a (n,1) vector.
2014-06-08 20:21:30 +02:00
2014-05-27 09:54:55 +02:00
2016-07-14 18:55:31 +02:00
#. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)
2014-05-27 22:02:13 +02:00
2014-05-29 21:48:26 +02:00
.. code-block:: python
2014-05-27 22:01:03 +02:00
# Author: Robert Kern
Z = np.ones(16,16)
k = 4
S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
np.arange(0, Z.shape[1], k), axis=1)
2014-05-27 22:01:03 +02:00
2016-07-14 18:55:31 +02:00
#. How to implement the Game of Life using numpy arrays? (★★★)
2015-02-26 18:24:23 +01:00
.. code-block:: python
# Author: Nicolas Rougier
def iterate(Z):
# Count neighbours
N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +
Z[1:-1,0:-2] + Z[1:-1,2:] +
Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:])
# Apply rules
birth = (N==3) & (Z[1:-1,1:-1]==0)
survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)
Z[...] = 0
Z[1:-1,1:-1][birth | survive] = 1
return Z
Z = np.random.randint(0,2,(50,50))
for i in range(100): Z = iterate(Z)
2016-03-08 21:02:50 +01:00
#. How to get the n largest values of an array (★★★)
2016-03-08 21:09:04 +01:00
.. code-block:: python
2016-03-08 21:02:50 +01:00
2016-03-08 21:09:04 +01:00
Z = np.arange(10000)
np.random.shuffle(Z)
n = 5
2016-03-08 21:02:50 +01:00
2016-03-08 21:09:04 +01:00
# Slow
print (Z[np.argsort(Z)[-n:]])
2016-03-08 21:02:50 +01:00
2016-03-08 21:09:04 +01:00
# Fast
print (Z[np.argpartition(-Z,n)[:n]])
2016-03-08 21:02:50 +01:00
#. Given an arbitrary number of vectors, build the cartesian product (every
2016-03-08 21:02:50 +01:00
combinations of every item) (★★★)
.. code-block:: python
# Author: Stefan Van der Walt
def cartesian(arrays):
arrays = [np.asarray(a) for a in arrays]
shape = (len(x) for x in arrays)
ix = np.indices(shape, dtype=int)
ix = ix.reshape(len(arrays), -1).T
for n, arr in enumerate(arrays):
ix[:, n] = arrays[n][ix[:, n]]
return ix
print (cartesian(([1, 2, 3], [4, 5], [6, 7])))
2015-11-02 21:41:40 +01:00
2016-07-14 18:55:31 +02:00
#. How to create a record array from a regular array? (★★★)
2015-11-02 21:41:40 +01:00
.. code-block:: python
Z = np.array([("Hello", 2.5, 3),
("World", 3.6, 2)])
R = np.core.records.fromarrays(Z.T,
names='col1, col2, col3',
formats = 'S8, f8, i8')
2016-07-14 18:55:31 +02:00
#. Consider a large vector Z, compute Z to the power of 3 using 3 different
2016-03-08 21:02:50 +01:00
methods (★★★)
2015-11-02 21:41:40 +01:00
.. code-block:: python
Author: Ryan G.
x = np.random.rand(5e7)
%timeit np.power(x,3)
1 loops, best of 3: 574 ms per loop
%timeit x*x*x
1 loops, best of 3: 429 ms per loop
%timeit np.einsum('i,i,i->i',x,x,x)
1 loops, best of 3: 244 ms per loop
#. 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
2016-07-14 18:55:31 +02:00
in B? (★★★)
.. code-block:: python
# Author: Gabe Schwartz
A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))
C = (A[..., np.newaxis, np.newaxis] == B)
rows = (C.sum(axis=(1,2,3)) >= B.shape[1]).nonzero()[0]
print(rows)
2016-03-08 21:02:50 +01:00
#. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)
.. code-block:: python
# Author: Robert Kern
Z = np.random.randint(0,5,(10,3))
E = np.logical_and.reduce(Z[:,1:] == Z[:,:-1], axis=1)
U = Z[~E]
print(Z)
print(U)
2016-03-08 21:02:50 +01:00
#. Convert a vector of ints into a matrix binary representation (★★★)
.. code-block:: python
# Author: Warren Weckesser
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])
B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])
# Author: Daniel T. McDonald
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))
2016-07-14 18:55:31 +02:00
#. Given a two dimensional array, how to extract unique rows? (★★★)
.. code-block:: python
# Author: Jaime Fernández del Río
Z = np.random.randint(0,2,(6,3))
T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))
_, idx = np.unique(T, return_index=True)
uZ = Z[idx]
print(uZ)
2015-11-02 21:41:40 +01:00
#. Considering 2 vectors A & B, write the einsum equivalent of inner, outer,
2016-03-08 21:02:50 +01:00
sum, and mul function (★★★)
2015-11-02 21:41:40 +01:00
.. code-block:: python
# Author: Alex Riley
# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/
np.einsum('i->', A) # np.sum(A)
np.einsum('i,i->i', A, B) # A * B
np.einsum('i,i', A, B) # np.inner(A, B)
np.einsum('i,j', A, B) # np.outer(A, B)
#. Considering a path described by two vectors (X,Y), how to sample it using
2016-07-14 18:55:31 +02:00
equidistant samples (★★★)?
2015-11-02 21:41:40 +01:00
.. code-block:: python
# Author: Bas Swinckels
phi = np.arange(0, 10*np.pi, 0.1)
a = 1
x = a*phi*np.cos(phi)
y = a*phi*np.sin(phi)
dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths
r = np.zeros_like(x)
r[1:] = np.cumsum(dr) # integrate path
r_int = np.linspace(0, r.max(), 200) # regular spaced path
x_int = np.interp(r_int, r, x) # integrate path
y_int = np.interp(r_int, r, y)
#. 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. (★★★)
.. code-block:: python
# Author: Evgeni Burovski
X = np.asarray([[1.0, 0.0, 3.0, 8.0],
[2.0, 0.0, 1.0, 1.0],
[1.5, 2.5, 1.0, 0.0]])
n = 4
M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)
M &= (X.sum(axis=-1) == n)
print(X[M])
2016-07-14 21:54:03 +02:00
2016-07-15 00:28:35 +02:00
#. 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). (★★★)
2016-07-14 21:54:03 +02:00
2016-07-15 00:29:32 +02:00
.. code-block:: python
2016-07-14 21:54:03 +02:00
2016-07-15 00:29:32 +02:00
# Author: Jessica B. Hamrick
2016-07-14 21:54:03 +02:00
2016-07-15 00:29:32 +02:00
X = np.random.randn(100) # random 1D array
N = 1000 # number of bootstrap samples
idx = np.random.randint(0, X.size, (N, X.size))
means = X[idx].mean(axis=1)
confint = np.percentile(means, [2.5, 97.5])
print(confint)