1 2 3 4 5 6 7 8 9 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 100 101 102 103 104 105 106 107 108 109 110
| import numpy as np
a = np.array([1,2,3,np.nan,5,6,7,np.nan]) a[~np.isnan(a)] array([ 1., 2., 3., 5., 6., 7.])
a = np.array([1,2,3,4,5]) b = np.array([4,5,6,7,8]) dist = np.linalg.norm(a-b) dist
a = np.array([1, 3, 7, 1, 2, 6, 0, 1]) doublediff = np.diff(np.sign(np.diff(a))) peak_locations = np.where(doublediff == -2)[0] + 1 peak_locations
a_2d = np.array([[3,3,3],[4,4,4],[5,5,5]]) b_1d = np.array([1,2,3]) a_2d - b_1d[:,None]
x = np.array([1, 2, 1, 1, 3, 4, 3, 1, 1, 2, 1, 1, 2]) n = 5
[i for i, v in enumerate(x) if v == 1][n-1]
np.where(x == 1)[0][n-1]
dt64 = np.datetime64('2018-02-25 22:10:10')
from datetime import datetime dt64.tolist()
dt64.astype(datetime) datetime.datetime(2018, 2, 25, 22, 10, 10)
np.random.seed(100) Z = np.random.randint(10, size=10) Z
def moving_average(a, n=3) : ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n moving_average(Z, n=3).round(2)
np.convolve(Z, np.ones(3)/3, mode='valid')
length = 10 start = 5 step = 3 def seq(start, length, step): end = start + (step*length) return np.arange(start, end, step) seq(start, length, step)
dates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-25'), 2) dates
filled_in = np.array([np.arange(date, (date+d)) for date, d in zip(dates, np.diff(dates))]).reshape(-1) output = np.hstack([filled_in, dates[-1]])
out = [] for date, d in zip(dates, np.diff(dates)): out.append(np.arange(date, (date+d))) filled_in = np.array(out).reshape(-1) output = np.hstack([filled_in, dates[-1]]) output
arr = np.arange(15) arr array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) def gen_strides(arr, stride_len=5, window_len=5): n_strides = (a.size-window_len)//stride_len + 1 return np.array([a[s:(s+window_len)] for s in np.arange(0, n_strides*stride_len, stride_len)]) gen_strides(np.arange(15), stride_len=2, window_len=4)
|