簡體   English   中英

如何將 numpy.sort 用於 ndarray

[英]How to use numpy.sort for ndarray

在我的程序中,我嘗試使用它們的索引獲取前 10 個數組項。 數組的類型是ndarray

for a in arr:
   print(a)

(0, 112354) 0.11235445
(0, 875) 0.155235445
(0, 6135) -0.14445445
...

我嘗試為此使用numpy.sort並將數組作為參數傳遞,但它沒有給出所需的結果。

如何獲得前 10 個數組項及其索引?

更新

pprint(arr)輸出是

<1x28382 sparse matrix of type '<class 'numpy.float64'>'
    with 18404 stored elements in Compressed Sparse Row format>

print(arr)返回:

 (0, 11098) 0.113315317878
  (0, 6775) 0.0513432082411
  (0, 5107) 0.0544519626112
  (0, 98)   0.059766413309
  (0, 27042)    0.104718642966
  (0, 22622)    0.104718642966
  (0, 6135) 0.104718642966

實際上arrsklearn.svm.SVC.coef_對象。

謝謝你的幫助。

由於這是一個稀疏矩陣,因此在a.data上工作更有效。

一個簡單的例子:

from numpy import *
import scipy
a=zeros(12,int)
a[:6]=range(6)
shuffle(a)
a=scipy.sparse.csr_matrix(a.reshape(4,3))
print(a.toarray());print(a)

# a is
[[4 0 1]
 [3 0 5]
 [2 0 0]
 [0 0 0]]

# or in csr format
(0, 1)  5.0
(0, 2)  3.0
(1, 2)  2.0
(3, 0)  1.0
(3, 1)  4.0

然后找到 n 個最大值,以及與 row 和 col 相關的索引:

n=3 # the three biggest 
bigs=a.data.argsort()[:-n-1:-1] 
r,c=a.nonzero()
R,C=r[bigs],c[bigs]
print("the 3 biggest are in ",*zip(R,C))

這給出了:

the 3 biggest are in  (0, 1) (3, 1) (0, 2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM