ここために
nzidx = np.where(x)
ranking = np.argsort(x[nzidx]) # append [::-1] for descending order
result = tuple(np.array(nzidx)[:, ranking])
要素は関係なく、次元のx[result]
によって取得することができる別の解決策です。
デモ:
>>
>>> x
array([[ 0. , -1.36688591, 0.12606516, -1.8546047 , 0. , 0.39758545],
[ 0.65160821, -1.80074214, 0. , 0. , 1.20758375, 0.33281977]])
>>> nzidx = np.where(x)
>>> ranking = np.argsort(x[nzidx])
>>> result = tuple(np.array(nzidx)[:, ranking])
>>>
>>> result
(array([0, 1, 0, 0, 1, 0, 1, 1]), array([3, 1, 1, 2, 5, 5, 0, 4]))
>>> x[result]
array([-1.8546047 , -1.80074214, -1.36688591, 0.12606516, 0.33281977,
0.39758545, 0.65160821, 1.20758375])
更新:ソートは行ごとにすべきかどう
私たちが使用できるリストの内包
nzidx = [np.where(r)[0] for r in x]
ranking = [np.argsort(r[idx]) for r, idx in zip(x, nzidx)]
result = [idx[rk] for idx, rk in zip(nzidx, ranking)]
または
nzidx = np.where(x)
blocks = np.searchsorted(nzidx[0], np.arange(1, x.shape[0]))
ranking = [np.argsort(r) for r in np.split(x[nzidx], blocks)]
result = [idx[rk] for idx, rk in zip(np.split(nzidx[1], blocks), ranking)]
デモ:
>>> x
array([[ 0. , 0. , 0. , 0. , 0.1218789 ,
0. , 0. , 0. ],
[ 0. , -0.6445128 , -0.00603869, 1.47947823, -1.4370367 ,
0. , 1.11606385, -1.22169137],
[ 0. , 0. , 0. , 1.54048119, -0.85764299,
0. , 0. , 0.32325807]])
>>> nzidx = np.where(x)
>>> blocks = np.searchsorted(nzidx[0], np.arange(1, x.shape[0]))
>>> ranking = [np.argsort(r) for r in np.split(x[nzidx], blocks)]
>>> result = [idx[rk] for idx, rk in zip(np.split(nzidx[1], blocks), ranking)]
>>> # package them
... [(r[idx], idx) for r, idx in zip(x, result)]
[(array([ 0.1218789]), array([4])), (array([-1.4370367 , -1.22169137, -0.6445128 , -0.00603869, 1.11606385,
1.47947823]), array([4, 7, 1, 2, 6, 3])), (array([-0.85764299, 0.32325807, 1.54048119]), array([4, 7, 3]))]
掲載ソリューションのいずれかがあなたのために働くましたか? – Divakar