Python3 中的 argsort [英] argsort in Python3

查看:56
本文介绍了Python3 中的 argsort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么在 Python2 和 Python3 中使用 argsort 会得到不同的结果.我的代码如下:

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]

在 Python2 中,freqrank 包含的结果如下:数组([4215, 2825, 7066, ..., 539, 3188, 5239]).然而,在Python3中,freqrank只包含array([0]),这个结果进一步导致最后一行代码出现IndexError: too many数组的索引.如何获得 freqrank 在 Python3 中包含排序列表的相同结果,就像在 Python2 中一样?或者,如何使上述代码在 Python3 中工作?谢谢.

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.

推荐答案

values()(和 keys())返回由 Python 3 上的 dict 支持的视图对象,而不是列表.numpy.array 无法将 dict 视图转换为数组.

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.

您可以在视图上调用 list 以获取列表,但与其这样做,我建议您完全消除 dict.你似乎没有做任何事情但是调用 keys()values() 就可以了.

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.

这篇关于Python3 中的 argsort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆