In [3]:
%autosave 20
import numpy as np
Autosaving every 20 seconds
In [12]:
a = np.array([1, 2, 3])
b = np.array([[1, 2, 3],
              [4, 5, 6]])
c = a - 7.5
c.dtype
Out[12]:
dtype('float64')
In [13]:
a == 2
Out[13]:
array([False,  True, False])
In [14]:
np.sin(a)
Out[14]:
array([0.84147098, 0.90929743, 0.14112001])
In [16]:
np.array_equal(np.sqrt(a), a**0.5)
Out[16]:
True
In [17]:
%timeit np.sqrt(a)
%timeit a**0.5
1.4 µs ± 2.38 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
2.56 µs ± 10.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [19]:
import timeit
timeit.timeit('1+2')
Out[19]:
0.01578044379130006
In [20]:
np.lookfor('arct')
Search results for 'arct'
-------------------------
numpy.arctan
    Trigonometric inverse tangent, element-wise.
numpy.arctan2
    Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly.
numpy.arctanh
    Inverse hyperbolic tangent element-wise.
numpy.ma.arctan
    Trigonometric inverse tangent, element-wise.
numpy.ma.arctan2
    Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly.
numpy.ma.arctanh
    Inverse hyperbolic tangent element-wise.
numpy.angle
    Return the angle of the complex argument.
numpy.arccos
    Trigonometric inverse cosine, element-wise.
numpy.arcsin
    Inverse sine, element-wise.
numpy.arccosh
    Inverse hyperbolic cosine, element-wise.
numpy.ma.angle
    Return the angle of the complex argument.
numpy.ma.arccos
    Trigonometric inverse cosine, element-wise.
numpy.ma.arcsin
    Inverse sine, element-wise.
numpy.ma.arccosh
    Inverse hyperbolic cosine, element-wise.
numpy.core.tests.test_ufunc.TestUfunc.test_all_ufunc
    Try to check presence and results of all ufuncs.
In [22]:
np.arctan(a)
Out[22]:
array([0.78539816, 1.10714872, 1.24904577])
In [27]:
np.lookfor('sqrt')
Search results for 'sqrt'
-------------------------
numpy.sqrt
    Return the positive square-root of an array, element-wise.
numpy.ma.sqrt
    Return the positive square-root of an array, element-wise.
numpy.abs
    Calculate the absolute value element-wise.
numpy.std
    Compute the standard deviation along the specified axis.
numpy.polynomial.chebyshev.chebweight
    The weight function of the Chebyshev polynomials.
numpy.sign
    Returns an element-wise indication of the sign of a number.
numpy.hypot
    Given the "legs" of a right triangle, return its hypotenuse.
numpy.kaiser
    Return the Kaiser window.
numpy.nanstd
    Compute the standard deviation along the specified axis, while
numpy.square
    Return the element-wise square of the input.
numpy.corrcoef
    Return Pearson product-moment correlation coefficients.
numpy.errstate
    errstate(**kwargs)
numpy.histogram
    Compute the histogram of a set of data.
numpy.ma.abs
    Calculate the absolute value element-wise.
numpy.ma.hypot
    Given the "legs" of a right triangle, return its hypotenuse.
numpy.testing.measure
    Return elapsed time for executing code in the namespace of the caller.
numpy.linalg.matrix_rank
    Return matrix rank of array using SVD method
numpy.testing.assert_array_equal
    Raises an AssertionError if two array_like objects are not equal.
numpy.polynomial.Hermite._fit
    Least squares fit of Hermite series to data.
numpy.polynomial.HermiteE._fit
    Least squares fit of Hermite series to data.
numpy.polynomial.Laguerre._fit
    Least squares fit of Laguerre series to data.
numpy.polynomial.chebyshev.chebgauss
    Gauss-Chebyshev quadrature.
numpy.core.tests.test_ufunc.TestUfunc.test_all_ufunc
    Try to check presence and results of all ufuncs.
In [44]:
print(np.sum(a))
print(np.prod(a))
print(np.std(a))
print(b)
c = np.arange(8).reshape(2, 2, 2)
print(c)
np.sum(c, axis=(0,1))
6
6
0.816496580927726
[[1 2 3]
 [4 5 6]]
[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]
Out[44]:
array([12, 16])
In [50]:
a = np.arange(10)
a.reshape(-1, 2).mean(axis=1)
Out[50]:
array([0.5, 2.5, 4.5, 6.5, 8.5])
In [53]:
a = np.arange(5)
b = np.arange(10).reshape(2, 5)
print(a)
print(b)
a + b
[0 1 2 3 4]
[[0 1 2 3 4]
 [5 6 7 8 9]]
Out[53]:
array([[ 0,  2,  4,  6,  8],
       [ 5,  7,  9, 11, 13]])
In [54]:
a = np.arange(5)
b = np.arange(10).reshape(2, 6)
print(a)
print(b)
a + b
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-54-452458d00ca1> in <module>()
      1 a = np.arange(5)
----> 2 b = np.arange(10).reshape(2, 6)
      3 print(a)
      4 print(b)
      5 a + b

ValueError: cannot reshape array of size 10 into shape (2,6)
In [58]:
a = np.arange(5)
b = np.arange(10).reshape(5, 2)
print(a)
print(b)
np.array_equal(a.reshape(-1, 1) + b, a[:,np.newaxis] + b)
[0 1 2 3 4]
[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]
Out[58]:
True
In [73]:
a = np.arange(16).reshape((2,) * 4)
print(a[np.newaxis,...,0].shape)
Out[73]:
(1, 2, 2, 2)
In [91]:
a = np.arange(16).reshape(4,4)
a[[2, 3], ::-1]
a[[2, 3], [1, 3]]
print(a[[(0, 1)], 3])
[[3 7]]
Out[91]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
In [92]:
a = np.arange(16).reshape(4,4)
idx = a % 3 == 0
a[idx]
Out[92]:
array([ 0,  3,  6,  9, 12, 15])
In [94]:
a = np.arange(16).reshape(4,4)
idx = [True, False, False, True]
a[idx, ::2]
Out[94]:
array([[ 0,  2],
       [12, 14]])
In [98]:
li = list(range(1024))
a = np.array(li)
% timeit [x**3 for x in li]
% timeit (a**3).tolist()
394 µs ± 379 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
30.8 µs ± 25.7 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [99]:
%%timeit
for i, x in enumerate(li):
    if x % 2 == 0:
        li[i] += 1
86.8 µs ± 159 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [101]:
%timeit a[a % 2 == 0] += 1
19.7 µs ± 23.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [105]:
a = np.arange(8).reshape(4, 2)
print(a)
for x in a:
    print('x =', x)
len(a)
[[0 1]
 [2 3]
 [4 5]
 [6 7]]
x = [0 1]
x = [2 3]
x = [4 5]
x = [6 7]
Out[105]:
4
In [108]:
for x in a.flat:
    print(x)
a.flatten()
0
1
2
3
4
5
6
7
In [111]:
for idx, x in np.ndenumerate(a):
    a[idx] += 1
    print(idx, x, a[idx])
(0, 0) 0 1
(0, 1) 1 2
(1, 0) 2 3
(1, 1) 3 4
(2, 0) 4 5
(2, 1) 5 6
(3, 0) 6 7
(3, 1) 7 8
In [112]:
for i in np.ndindex((5, 3)):
    print(i)
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
(3, 0)
(3, 1)
(3, 2)
(4, 0)
(4, 1)
(4, 2)
In [115]:
np.r_[0:5, [1, 2, 3], 0:1:11j]
Out[115]:
array([0. , 1. , 2. , 3. , 4. , 1. , 2. , 3. , 0. , 0.1, 0.2, 0.3, 0.4,
       0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
In [124]:
X, Y = np.mgrid[0:3, 0:4]
print(X, '\n', Y)
[[0 0 0 0]
 [1 1 1 1]
 [2 2 2 2]] 
 [[0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]]
In [126]:
a = np.arange(5)
b = np.ones_like(a)
np.concatenate((a, b))
Out[126]:
array([0, 1, 2, 3, 4, 1, 1, 1, 1, 1])
In [131]:
a = np.arange(0, 4).reshape(2, 2)
b = np.arange(4, 8).reshape(2, 2)
c = np.arange(8, 12).reshape(2, 2)
print(a)
print(b)
print(c)

np.concatenate((a, b, c), axis=1)
# np.hstack()
# np.vstack()
[[0 1]
 [2 3]]
[[4 5]
 [6 7]]
[[ 8  9]
 [10 11]]
Out[131]:
array([[ 0,  1,  4,  5,  8,  9],
       [ 2,  3,  6,  7, 10, 11]])
In [143]:
stack = np.stack((a, b, c), axis=-1)
np.array_equal(stack[...,2], c)
print(a)
print(b)
print(c)
stack
[[0 1]
 [2 3]]
[[4 5]
 [6 7]]
[[ 8  9]
 [10 11]]
Out[143]:
array([[[ 0,  4,  8],
        [ 1,  5,  9]],

       [[ 2,  6, 10],
        [ 3,  7, 11]]])
In [146]:
r = np.r_[
    0:5,
    0:1:6j,
    np.array([1,2,3]),
    [5]*3
]
con = np.concatenate((
    np.arange(5),
    np.linspace(0, 1, 6),
    np.array([1,2,3]),
    np.full(3, 5),
))
print(r)
print(con)
[0.  1.  2.  3.  4.  0.  0.2 0.4 0.6 0.8 1.  1.  2.  3.  5.  5.  5. ]
[0.  1.  2.  3.  4.  0.  0.2 0.4 0.6 0.8 1.  1.  2.  3.  5.  5.  5. ]
In [149]:
a = np.linspace(0, 1, 10)
np.fft.fft(a)
Out[149]:
array([ 5.        +0.00000000e+00j, -0.55555556+1.70982419e+00j,
       -0.55555556+7.64656622e-01j, -0.55555556+4.03634738e-01j,
       -0.55555556+1.80510942e-01j, -0.55555556-1.66533454e-16j,
       -0.55555556-1.80510942e-01j, -0.55555556-4.03634738e-01j,
       -0.55555556-7.64656622e-01j, -0.55555556-1.70982419e+00j])
In [152]:
np.savetxt('a.dat', a)
a1 = np.loadtxt('a.dat')
a1
Out[152]:
array([0.        , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
       0.55555556, 0.66666667, 0.77777778, 0.88888889, 1.        ])
In [161]:
np.rec.array(
    {'x': [1,2,3], 'y': [0.5, 2.7, 3.1], 'z': ['a', 'b', 'c']}
)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-161-cef2d27416f4> in <module>()
      1 np.rec.array(
----> 2     {'x': [1,2,3], 'y': [0.5, 2.7, 3.1], 'z': ['a', 'b', 'c']}
      3 )

/opt/conda/lib/python3.6/site-packages/numpy/core/records.py in array(obj, dtype, shape, offset, strides, formats, names, titles, aligned, byteorder, copy)
    873         interface = getattr(obj, "__array_interface__", None)
    874         if interface is None or not isinstance(interface, dict):
--> 875             raise ValueError("Unknown input type")
    876         obj = sb.array(obj)
    877         if dtype is not None and (obj.dtype != dtype):

ValueError: Unknown input type
In [184]:
a = np.array([(1.0, 2), (3.0, 4)],
             dtype=[('x', float), ('1', int)])
a['x']
r = np.rec.array(a)
r.x
Out[184]:
array([1., 3.])
In [189]:
a = np.arange(5)
ma = np.ma.masked_array(a, a % 2 == 0)
print(ma)
ma.sum()
[-- 1 -- 3 --]
Out[189]:
4
In [191]:
np.linalg.lstsq
In [193]:
np.poly
In [196]:
a = np.logspace(0, 1, 11) #  == 10**np.linspace(0, 1, 11)
np.diff(a)
Out[196]:
array([0.25892541, 0.32596778, 0.41036912, 0.51662412, 0.65039123,
       0.81879405, 1.03080063, 1.29770111, 1.6337089 , 2.05671765])
In [198]:
np.gradient(a)