```python
import numpy as np
```

# Array Creation

## Creating arrays from lists


```python
x = np.array([2, 3.5, -1, 7.3, 0])
x
```




    array([ 2. ,  3.5, -1. ,  7.3,  0. ])




```python
A = np.array([[1, -3, 2],[2, 0, 1]])
A
```




    array([[ 1, -3,  2],
           [ 2,  0,  1]])




```python
x = np.array([i**2 for i in range(5)])
x
```




    array([ 0,  1,  4,  9, 16])



## How to specify the type of array elements.


```python
x = np.array([1.2, 3.4, -2.0], dtype=np.float32)
x
```




    array([ 1.20000005,  3.4000001 , -2.        ], dtype=float32)




```python
x = np.array([2**300], dtype=np.float64)
x
```




    array([  2.03703598e+90])



## Creating an empty array with a given shape


```python
x = np.empty((3,2))
x
```




    array([[  8.39911598e-322,   0.00000000e+000],
           [  0.00000000e+000,   0.00000000e+000],
           [  0.00000000e+000,   0.00000000e+000]])




```python
x = np.empty((2,4), dtype=np.int16)
x
```




    array([[10,  0, 20,  0],
           [30,  0, 40,  0]], dtype=int16)



## How to create an array with zeros, ones and with a single value


```python
x = np.zeros((2,3))
x
```




    array([[ 0.,  0.,  0.],
           [ 0.,  0.,  0.]])




```python
x = np.zeros((2,3), dtype=np.int64)
x
```




    array([[0, 0, 0],
           [0, 0, 0]], dtype=int64)




```python
x = np.ones((4,4))
x
```




    array([[ 1.,  1.,  1.,  1.],
           [ 1.,  1.,  1.,  1.],
           [ 1.,  1.,  1.,  1.],
           [ 1.,  1.,  1.,  1.]])




```python
x = np.full((3,1), -2.5)
x
```




    array([[-2.5],
           [-2.5],
           [-2.5]])



## Creating an array with equally spaced elements


```python
x = np.arange(1.1, 1.9, 0.2)
x
```




    array([ 1.1,  1.3,  1.5,  1.7])




```python
x = np.arange(2.5, 6.5)
x
```




    array([ 2.5,  3.5,  4.5,  5.5])




```python
x = np.arange(3.2)
x
```




    array([ 0.,  1.,  2.,  3.])




```python
x = np.arange(0.9, 4.9, dtype=np.int64)
x
```




    array([0, 1, 2, 3], dtype=int64)




```python
x = np.arange(0, 4)
x
```




    array([0, 1, 2, 3])




```python
x = np.linspace(1.2, 3.2, 11)
x
```




    array([ 1.2,  1.4,  1.6,  1.8,  2. ,  2.2,  2.4,  2.6,  2.8,  3. ,  3.2])



## Creating arrays with repreated elements


```python
x = np.repeat(1.2, 3)
x
```




    array([ 1.2,  1.2,  1.2])




```python
x = np.array([[1,2,3],[4,5,6]])
y = np.repeat(x, 2)
y
```




    array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6])




```python
y = np.repeat(x, 2, axis=0)
y
```




    array([[1, 2, 3],
           [1, 2, 3],
           [4, 5, 6],
           [4, 5, 6]])




```python
y = np.repeat(x, 2, axis=1)
y
```




    array([[1, 1, 2, 2, 3, 3],
           [4, 4, 5, 5, 6, 6]])




```python
y = np.repeat(x, [2, 1, 2], axis=1)
y
```




    array([[1, 1, 2, 3, 3],
           [4, 4, 5, 6, 6]])




```python
x = np.array([[1,2,3,4],[5,6,7,8]])
y = np.repeat(x, [1,0,1,0], axis=1)
y
```




    array([[1, 3],
           [5, 7]])



## Creating an array by tiling another array


```python
x = np.array([[1,2],[3,4]])
y = np.tile(x,(2,3))
y
```




    array([[1, 2, 1, 2, 1, 2],
           [3, 4, 3, 4, 3, 4],
           [1, 2, 1, 2, 1, 2],
           [3, 4, 3, 4, 3, 4]])



## Querying and changing the shape of an array


```python
x = np.array([[1,2,3,4,5,6],[7,8,9,10,11,12]])
x.shape
```




    (2, 6)




```python
x.shape
```




    (2, 6)




```python
x.shape = (4,3)
x
```




    array([[ 1,  2,  3],
           [ 4,  5,  6],
           [ 7,  8,  9],
           [10, 11, 12]])



## Creating arrays with the same shape as another array


```python
x = np.array([[1,2],[3,4],[5,6]], dtype=np.float64)
y = np.zeros_like(x)
y
```




    array([[ 0.,  0.],
           [ 0.,  0.],
           [ 0.,  0.]])




```python
y = np.zeros(x.shape)
y
```




    array([[ 0.,  0.],
           [ 0.,  0.],
           [ 0.,  0.]])




```python
x = np.array([[1,1],[2,2]])
z = np.full_like(x, 6.2)
z
```




    array([[6, 6],
           [6, 6]])




```python
z = np.full_like(x, 6.2, dtype=np.float64)
z
```




    array([[ 6.2,  6.2],
           [ 6.2,  6.2]])



## How to join arrays


```python
x = np.array([1,2,3])
y = np.array([4,5,6])
z = np.array([7,8,9])
w = np.column_stack([x,y,z])
w
```




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




```python
x = np.array([[1,2,3],[4,5,6]])
y = np.array([[10,20,30],[40,50,60],[70,80,90]])
z = np.concatenate([x,y])
z
```




    array([[ 1,  2,  3],
           [ 4,  5,  6],
           [10, 20, 30],
           [40, 50, 60],
           [70, 80, 90]])




```python
x = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])
y = np.array([[10,20],[30,40]])
z = np.concatenate([x,y], axis=1)
z
```




    array([[ 1,  2,  3,  4, 10, 20],
           [ 5,  6,  7,  8, 30, 40]])




```python
x = np.array([[1,2,3],[4,5,6]])
y = np.array([[10,20,30],[40,50,60],[70,80,90]])
z = np.vstack([x,y])
z
```




    array([[ 1,  2,  3],
           [ 4,  5,  6],
           [10, 20, 30],
           [40, 50, 60],
           [70, 80, 90]])




```python
x = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])
y = np.array([[10,20],[30,40]])
z = np.hstack([x,y])
z
```




    array([[ 1,  2,  3,  4, 10, 20],
           [ 5,  6,  7,  8, 30, 40]])




```python
x = np.array([[1,2,3],[4,5,6]])
y = np.array([[7,8,9]])
z = np.append(x, y , axis=0)
z
```




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




```python
x = np.array([[1,2],[3,4],[5,6]])
y = np.array([[10],[20],[30]])
z = np.append(x, y, axis=1)
z
```




    array([[ 1,  2, 10],
           [ 3,  4, 20],
           [ 5,  6, 30]])



# Storage and retrieval of NumPy arrays

## How to store an array using text format


```python
x = np.random.rand(200, 300)
np.savetxt('array_x.txt', x)
```


```python
m, n = 10, 5
x = np.random.rand(m, n)
columns = ','.join(['Column {}'.format(str(i+1)) for i in range(n)])
np.savetxt('array_x.csv', x, fmt='%10.8f', 
           delimiter=',', header=columns, comments='')
```

## How to load an stored in text format


```python
x = np.loadtxt('array_x.txt')
```


```python
x[0:3, 0:3]
```




    array([[ 0.38178858,  0.61616081,  0.17321243],
           [ 0.10649178,  0.9364898 ,  0.69948501],
           [ 0.80312438,  0.36077361,  0.32711772]])




```python
x = np.loadtxt('employees.txt', delimiter=',',
               skiprows=1, usecols=(1,3,4))
```


```python
x
```




    array([[  1.01000000e+02,   4.20000000e+04,   5.00000000e+00],
           [  2.03000000e+02,   3.10000000e+04,   3.00000000e+00],
           [  1.05000000e+02,   6.70000000e+04,   8.00000000e+00]])



## How to store a single array in binary format


```python
x = np.random.rand(200, 300)
np.save('array_x.npy', x)
```


```python
x[:3,:3]
```




    array([[ 0.03679544,  0.52550094,  0.22047317],
           [ 0.9966285 ,  0.00323506,  0.64991816],
           [ 0.85757749,  0.2426703 ,  0.68695005]])



## How to store multiple arrays in binary format


```python
x = np.random.rand(200, 300)
y = np.random.rand(30)
z = np.random.rand(10, 5, 7)
```


```python
x[:3, :3]
```




    array([[ 0.41517967,  0.70143059,  0.00441163],
           [ 0.72653597,  0.03495698,  0.70568342],
           [ 0.90863073,  0.4179005 ,  0.34296939]])




```python
y[:5]
```




    array([ 0.54610691,  0.36904357,  0.56619923,  0.82599276,  0.90303479])




```python
z[:2,:2,:2]
```




    array([[[ 0.55990605,  0.17889199],
            [ 0.10774937,  0.21515745]],
    
           [[ 0.95836664,  0.2990247 ],
            [ 0.21513495,  0.19478542]]])




```python
np.savez('arrays_xyz.npz', xfile=x, yfile=y, zfile=z)
```


```python
np.savez_compressed('arrays_xyz_c.npz', xfile=x, yfile=y, zfile=z)
```


```python
x = np.load('array_x.npy')
```


```python
x[:3, :3]
```




    array([[ 0.03679544,  0.52550094,  0.22047317],
           [ 0.9966285 ,  0.00323506,  0.64991816],
           [ 0.85757749,  0.2426703 ,  0.68695005]])




```python
arrays = np.load('arrays_xyz.npz')
x, y, z = [arrays[name] for name in ['xfile', 'yfile', 'zfile']]
```


```python
x[:3, :3]
```




    array([[ 0.41517967,  0.70143059,  0.00441163],
           [ 0.72653597,  0.03495698,  0.70568342],
           [ 0.90863073,  0.4179005 ,  0.34296939]])




```python
y[:5]
```




    array([ 0.54610691,  0.36904357,  0.56619923,  0.82599276,  0.90303479])




```python
z[:2,:2,:2]
```




    array([[[ 0.55990605,  0.17889199],
            [ 0.10774937,  0.21515745]],
    
           [[ 0.95836664,  0.2990247 ],
            [ 0.21513495,  0.19478542]]])




```python
arrays.keys()
```




    ['xfile', 'yfile', 'zfile']



# Indexing


```python
m = n = 10
x = np.array([np.arange(n) + m*i for i in range(n)])
```


```python
def dumpArray(arr):
    print('\n'.join([
        ' '.join(['{:02d}'.format(elem) for elem in row])
        for row in arr
    ]))
```


```python
dumpArray(x)
```

    00 01 02 03 04 05 06 07 08 09
    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
    50 51 52 53 54 55 56 57 58 59
    60 61 62 63 64 65 66 67 68 69
    70 71 72 73 74 75 76 77 78 79
    80 81 82 83 84 85 86 87 88 89
    90 91 92 93 94 95 96 97 98 99



```python
y = x[2:4, 3:6]
dumpArray(y)
```

    23 24 25
    33 34 35



```python
y = x[1:5:2, 2:10:3]
dumpArray(y)
```

    12 15 18
    32 35 38



```python
y = x[4:1:-1, 2]
y
```




    array([42, 32, 22])




```python
y = x[:, 5]
y
```




    array([ 5, 15, 25, 35, 45, 55, 65, 75, 85, 95])




```python
xx = x.copy()
xx[2:-2, 2:-2] = np.zeros((6, 6), dtype=np.int64)
dumpArray(xx)
```

    00 01 02 03 04 05 06 07 08 09
    10 11 12 13 14 15 16 17 18 19
    20 21 00 00 00 00 00 00 28 29
    30 31 00 00 00 00 00 00 38 39
    40 41 00 00 00 00 00 00 48 49
    50 51 00 00 00 00 00 00 58 59
    60 61 00 00 00 00 00 00 68 69
    70 71 00 00 00 00 00 00 78 79
    80 81 82 83 84 85 86 87 88 89
    90 91 92 93 94 95 96 97 98 99



```python
xx = x.copy()
y = xx[:]
y[1,1] = 0
dumpArray(xx)
```

    00 01 02 03 04 05 06 07 08 09
    10 00 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
    50 51 52 53 54 55 56 57 58 59
    60 61 62 63 64 65 66 67 68 69
    70 71 72 73 74 75 76 77 78 79
    80 81 82 83 84 85 86 87 88 89
    90 91 92 93 94 95 96 97 98 99



```python
xx = x.copy()
y[:] = xx
y[1,1] = 0
dumpArray(xx)
```

    00 01 02 03 04 05 06 07 08 09
    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
    50 51 52 53 54 55 56 57 58 59
    60 61 62 63 64 65 66 67 68 69
    70 71 72 73 74 75 76 77 78 79
    80 81 82 83 84 85 86 87 88 89
    90 91 92 93 94 95 96 97 98 99



```python
y = x[[2, 3, 1], [0, 3, 5]]
y
```




    array([20, 33, 15])




```python
y = x[:, [5, 2, -1]]
dumpArray(y)
```

    05 02 09
    15 12 19
    25 22 29
    35 32 39
    45 42 49
    55 52 59
    65 62 69
    75 72 79
    85 82 89
    95 92 99



```python
y = x[[2, 0, 3],:][:,[-2, 1]]
dumpArray(y)
```

    28 21
    08 01
    38 31



```python
condition = x > 87
y = x[condition]
y
```




    array([88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])




```python
x = np.array([[-1, 2, 4], [2, -3, 1], [2, 4, 0], 
              [-5, 4, 3], [3, 1, 1], [2, 0, -4]])
row_sums = x.sum(axis=1)
y = x[row_sums % 2 == 0, :]
y
```




    array([[ 2, -3,  1],
           [ 2,  4,  0],
           [-5,  4,  3],
           [ 2,  0, -4]])




```python
x.sum(axis=1)
```




    array([ 5,  0,  6,  2,  5, -2])




```python
mask = np.sum(x, axis=1) % 2 == 0
mask
```




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




```python
x[mask, :]
```




    array([[ 2, -3,  1],
           [ 2,  4,  0],
           [-5,  4,  3],
           [ 2,  0, -4]])



## Operations on arrays


```python
x = np.pi * np.arange(0, 2, 0.25)
y = np.sin(x)
y
```




    array([  0.00000000e+00,   7.07106781e-01,   1.00000000e+00,
             7.07106781e-01,   1.22464680e-16,  -7.07106781e-01,
            -1.00000000e+00,  -7.07106781e-01])




```python
x = np.array([1.2, -0.23, 3.4])
y = np.array([2.4, -1.7, -5.4])
z = x + y
z
```




    array([ 3.6 , -1.93, -2.  ])




```python
x = np.array([1.2, -0.23, 3.4])
z = 1 + x
z
```




    array([ 2.2 ,  0.77,  4.4 ])




```python
np.array([1.0])+x
```




    array([ 2.2 ,  0.77,  4.4 ])




```python
np.array([1.0, 1.0, 1.0]) + x
```




    array([ 2.2 ,  0.77,  4.4 ])




```python
np.array([1.0]).shape
```




    (1,)




```python
x = np.arange(12, dtype=np.float64).reshape(3, 4)
y = np.array([1, 2, 3])
z = y + x
z
```


```python
x = np.arange(12, dtype=np.float64).reshape(3, 4)
y = np.array([[1], [2], [3]])
z = y + x
z
```




    array([[  1.,   2.,   3.,   4.],
           [  6.,   7.,   8.,   9.],
           [ 11.,  12.,  13.,  14.]])




```python
yy = np.array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]])
yy
```




    array([[1, 1, 1, 1],
           [2, 2, 2, 2],
           [3, 3, 3, 3]])




```python
yy + x
```




    array([[  1.,   2.,   3.,   4.],
           [  6.,   7.,   8.,   9.],
           [ 11.,  12.,  13.,  14.]])



## Computing the matrix product of two arrays


```python
A = np.array([[2.3, 4.5, -3.1],
              [1.2, 3.2,  4.0]])
B = np.array([[ 2.1, -4.6, 0.5, 2.2],
              [-1.2, -3.0, 1.7, 3.2],
              [ 3.1,  2.6, 1.1, 2.3]])
C = A.dot(B)
C
```




    array([[-10.18, -32.14,   5.39,  12.33],
           [ 11.08,  -4.72,  10.44,  22.08]])




```python
u = np.array([0.5, 2.3, -4.0])
v = np.array([3.2, -5.4])
w = A.dot(u)
z = v.dot(A)
```


```python
w
```




    array([ 23.9 ,  -8.04])




```python
z
```




    array([[  1.,   2.,   3.,   4.],
           [  6.,   7.,   8.,   9.],
           [ 11.,  12.,  13.,  14.]])



# Masked arrays


```python
import numpy.ma as ma
```

## Create masked array from an explicit mask


```python
x = np.array([1.0, 3.2, -2.1, 4.3, 5.4])
xm = ma.masked_array(x, [0, 0, 1, 0, 0])
xm
```




    masked_array(data = [1.0 3.2 -- 4.3 5.4],
                 mask = [False False  True False False],
           fill_value = 1e+20)




```python
print(repr(xm))
```

    masked_array(data = [1.0 3.2 -- 4.3 5.4],
                 mask = [False False  True False False],
           fill_value = 1e+20)
    


## Create masked array from a condition


```python
x = np.array([
    [i+j for j in range(i, i+5)] 
    for i in range(5)])
xm = ma.masked_inside(x, 4, 6)
print(xm)
```

    [[0 1 2 3 --]
     [2 3 -- -- --]
     [-- -- -- 7 8]
     [-- 7 8 9 10]
     [8 9 10 11 12]]



```python
print(x)
```

    [[ 0  1  2  3  4]
     [ 2  3  4  5  6]
     [ 4  5  6  7  8]
     [ 6  7  8  9 10]
     [ 8  9 10 11 12]]



```python
xm = ma.masked_outside(x, 4, 6)
print(xm)
```

    [[-- -- -- -- 4]
     [-- -- 4 5 6]
     [4 5 6 -- --]
     [6 -- -- -- --]
     [-- -- -- -- --]]



```python
def digit_sum(n):
    return n // 10 + n % 10
x = np.array([[10*i+j for j in range(1,7)] for i in range(1,7)])
condition = (digit_sum(x) > 5) & (digit_sum(x) < 9)
xm = ma.masked_where(condition, x)
print(xm)
```

    [[11 12 13 14 -- --]
     [21 22 23 -- -- --]
     [31 32 -- -- -- 36]
     [41 -- -- -- 45 46]
     [-- -- -- 54 55 56]
     [-- -- 63 64 65 66]]



```python
print(x)
```

    [[11 12 13 14 15 16]
     [21 22 23 24 25 26]
     [31 32 33 34 35 36]
     [41 42 43 44 45 46]
     [51 52 53 54 55 56]
     [61 62 63 64 65 66]]



```python
digit_sum(x)
```




    array([[ 2,  3,  4,  5,  6,  7],
           [ 3,  4,  5,  6,  7,  8],
           [ 4,  5,  6,  7,  8,  9],
           [ 5,  6,  7,  8,  9, 10],
           [ 6,  7,  8,  9, 10, 11],
           [ 7,  8,  9, 10, 11, 12]], dtype=int32)




```python
x
```




    array([[11, 12, 13, 14, 15, 16],
           [21, 22, 23, 24, 25, 26],
           [31, 32, 33, 34, 35, 36],
           [41, 42, 43, 44, 45, 46],
           [51, 52, 53, 54, 55, 56],
           [61, 62, 63, 64, 65, 66]])




```python
(digit_sum(x) > 4) & (digit_sum(x) < 8)
```




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




```python
digit_sum(x) < 8
```




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



# Object arrays


```python
x = np.array([2.5, 'a string', [2,4], {'a':0, 'b':1}, np.array([2,3])])
```


```python
x
```




    array([2.5, 'a string', list([2, 4]), {'a': 0, 'b': 1}, array([2, 3])], dtype=object)




```python
[type(item) for item in x]
```




    [float, str, list, dict, numpy.ndarray]




```python
x = np.empty((2,2), dtype=np.object)
x
```




    array([[None, None],
           [None, None]], dtype=object)



# Symbolic function


```python
from sympy import *
init_printing(use_latex=True)
```


```python
r, theta = symbols('r, theta')
x = r * cos(theta)
y = r * sin(theta)
x, y
```


```python
polar_to_rectangular = lambdify((r, theta), (x, y), modules='numpy')
```


```python
r_values = np.array([2, 1.5, -3])
theta_values = np.array([np.pi/4, np.pi/2, -np.pi])
xvalues, yvalues = polar_to_rectangular(r_values, theta_values)
```


```python
xvalues
```




    array([  1.41421356e+00,   9.18485099e-17,   3.00000000e+00])




```python
yvalues
```




    array([  1.41421356e+00,   1.50000000e+00,   3.67394040e-16])




```python
%matplotlib inline
import matplotlib.pyplot as plt
r = 4
theta_values = np.linspace(0, 2*np.pi, 300)
xvalues, yvalues = polar_to_rectangular(r, theta_values)
plt.figure(figsize=(5,5))
plt.plot(xvalues, yvalues)
None
```


```python

```


```python

```

5de27f51515e6a39ce75cde8a783d95ad0a50d97
ipynb
Jupyter Notebook
Chapter02/Getting Started with Numpy.ipynb
PacktPublishing/SciPy-Recipes
fdea8e3bd6b161402ed824624819aa788e544eed
MIT
2017-12-28T05:01:19.000Z
2021-11-08T13:10:39.000Z
Chapter02/Getting Started with Numpy.ipynb
PacktPublishing/SciPy-Recipes
fdea8e3bd6b161402ed824624819aa788e544eed
MIT
Chapter02/Getting Started with Numpy.ipynb
PacktPublishing/SciPy-Recipes
fdea8e3bd6b161402ed824624819aa788e544eed
MIT
2017-12-24T09:25:55.000Z
2020-02-17T22:57:17.000Z
Qwen/Qwen-72B
1. YES
2. YES