Python3 中的 argsort

编程入门 行业动态 更新时间:2024-10-28 22:23:22
本文介绍了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

本文发布于:2023-06-08 14:31:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/583121.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:argsort

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!