Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

python 2.7 - argsort in Python3

I am wondering why I get different results by using argsort in Python2 and Python3. My codes are as follows:

## Import Data
allWrdMat10 = pd.read_csv("../../data/allWrdMat10.csv.gz", 
    encoding='CP932')

## Set X as CSR Sparse Matrix
X = np.array(allWrdMat10)
X = sp.csr_matrix(X)

dict_index = {t:i for i,t in enumerate(allWrdMat10.columns)}

freqrank = np.array(dict_index.values()).argsort()

X_transform = X[:, freqrank < 1000].transpose().toarray()

freq1000terms = dict_index.keys()
freq1000terms = np.array(freq1000terms)[freqrank < 1000]

In Python2, freqrank contains the results as: array([4215, 2825, 7066, ..., 539, 3188, 5239]). However, in Python3, freqrank only contains array([0]), and this result further causes an error in the last line of codes as IndexError: too many indices for array. How can I get the same results that freqrank contains the sorted list in Python3 as I have in Python2? Or, how can I make the codes above work in Python3? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

values() (and keys()) return view objects backed by the dict on Python 3, rather than lists. numpy.array can't convert a dict view to an array.

You can call list on the views to get a list, but rather than doing that, I'd recommend eliminating the dict entirely. You don't seem to be doing anything but calling keys() and values() on it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...