I am going to sort the following 2D and 1D numpy arrays based on the 1D-array values, but ValueError is raised:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The arrays are:
import numpy as np
a = np.array(
[[0, 1, 0, 1, 1, 1, 1],
[1, 0, 0, 1, 1, 0, 1],
[0, 1, 1, 1, 1, 0, 0,],
[0, 0, 0, 0, 1, 0, 0,],
[0, 0, 1, 0, 1, 1, 0,]])
b = np.array(
[[ -9., 6.],
[ -5., -6.],
[ -9., -4.],
[ -4., 2.],
[-13., 3.]])
c = np.array([ 4., 2., 1., 6., 1.])
c, a, b = zip(*sorted(zip(c,a,b)))
To clarify, how to sort the values of a, b, c based the values of c?
CodePudding user response:
IIUC, this is a perfect use case for numpy.argsort
:
idx = np.argsort(c)
c[idx]
# array([1., 1., 2., 4., 6.])
a[idx]
# array([[0, 1, 1, 1, 1, 0, 0],
# [0, 0, 1, 0, 1, 1, 0],
# [1, 0, 0, 1, 1, 0, 1],
# [0, 1, 0, 1, 1, 1, 1],
# [0, 0, 0, 0, 1, 0, 0]])
b[idx]
# array([[ -9., -4.],
# [-13., 3.],
# [ -5., -6.],
# [ -9., 6.],
# [ -4., 2.]])