Let's say I have two arrays like:
a = array([ 0.36981727, 0.06066488, 0.73031016])
b = array([[ 0.12375904, 0.11647815, 0.56665118],
[ 0.9421819 , 0.58797789, 0.26831203],
[ 0.25769 , 0.02517343, 0.76701222]])
where each element of a corresponds to one array of b. Now in order to sort 'a' and also keep track of its corresponding vectors in b I do:
ziped_and_sorted = np.array(sorted(zip(a,b), key=operation.itemgetter(0), reverese =True),'object')
then I need to split a and b again, so:
a = ziped_and_sorted[:,0]
In [158]: a
Out[158]: array([0.369817272838, 0.0606648844006, 0.730310164248], dtype=object)
b = ziped_and_sorted[:,1]
In [157]: b
Out[157]:
array([[ 0.12375904 0.11647815 0.56665118],
[ 0.9421819 0.58797789 0.26831203],
[ 0.25769 0.02517343 0.76701222]], dtype=object)
The problem is b.shape returns (3,)instead of (3,3). It is important because I need to do a matrix multiplication with b and the problem causes a dimension mismatched error.
P.S: If you have better solution, please suggest it.
This is because b is a ndarray of ndarray, but not a 2-dim ndarray.
You can use numpy.argsort to do this quickly:
import numpy as np
a = np.random.randint(0, 100, 5)
b = np.random.randint(0, 5, (5, 5))
print a
print b
idx = np.argsort(a)[::-1]
print a[idx]
print b[idx]
output is:
[27 65 8 19 32]
[[4 4 1 4 4]
[1 3 4 3 3]
[3 4 2 1 0]
[1 0 1 0 4]
[1 4 1 1 4]]
[65 32 27 19 8]
[[1 3 4 3 3]
[1 4 1 1 4]
[4 4 1 4 4]
[1 0 1 0 4]
[3 4 2 1 0]]
if you want to use sorted you can use numpy.vstack to convert a list of array to a 2-dim ndarray:
ziped_and_sorted = sorted(zip(a,b), key=operator.itemgetter(0), reverse=True)
np.vstack([row[1] for row in ziped_and_sorted])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With