Skip to content

Instantly share code, notes, and snippets.

@travis23
Last active August 8, 2019 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travis23/e9a23f411eca9ca2da176369f682774f to your computer and use it in GitHub Desktop.
Save travis23/e9a23f411eca9ca2da176369f682774f to your computer and use it in GitHub Desktop.
[sort matched arrays pairs] #python #numpy #argsort #unique #timeseries #monotonic #strictly_increasing
# Sometimes timeseries need to be concatenated and then sorted so that the time vector is monotonic.
# ---- Monotonic in x, but not strictly increasing
# ********************************************************************************
x1 = np.array([1, 2, 3, 4, 4]) # Not all of the values are unique
y1 = np.array([10, 20, 30, 42, 40])
x2 = np.array([1.5, 2.5, 3.5, 4.5])
y2 = np.array([15, 25, 35, 45])
x_ = np.concatenate((x1, x2))
# [1. 2. 3. 4. 4. 1.5 2.5 3.5 4.5]
y_ = np.concatenate((y1, y2))
# [10 20 30 42 40 15 25 35 45]
sort_index = np.argsort(x_)
# [0 5 1 6 2 7 3 4 8]
x = x_[sort_index]
# [1. 1.5 2. 2.5 3. 3.5 4. 4. 4.5]
y = y_[sort_index]
# [10 15 20 25 30 35 42 40 45]
# ---- Strictly increasing in x
# *******************************************************************************
sort_index = np.unique(x_, return_index=True)[1]
# [0 5 1 6 2 7 3 8]
x = x_[sort_index]
# [1. 1.5 2. 2.5 3. 3.5 4. 4.5]
y = y_[sort_index]
# [10 15 20 25 30 35 42 45]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment