TypeError通过索引访问coo_matrix - python

我有coo_matrix X和索引trn_idx,通过它们我可以访问该maxtrix

print (type(X  ), X.shape)
print (type(trn_idx), trn_idx.shape)

<class 'scipy.sparse.coo.coo_matrix'> (1503424, 2795253)
<class 'numpy.ndarray'> (1202739,)

这样调用:

X[trn_idx]
TypeError: only integer scalar arrays can be converted to a scalar index

可以这样:

 X[trn_idx.astype(int)] #same error

如何通过索引访问?

python参考方案

coo_matrix类不支持索引。您必须将其转换为其他稀疏格式。

这是一个带有小coo_matrix的示例:

In [19]: import numpy as np

In [20]: from scipy.sparse import coo_matrix

In [21]: m = coo_matrix([[0, 0, 0, 1], [2, 0, 0 ,0], [0, 0, 0, 0], [0, 3, 4, 0]])

尝试索引m失败:

In [22]: m[0,0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-1f78c188393f> in <module>()
----> 1 m[0,0]

TypeError: 'coo_matrix' object is not subscriptable

In [23]: idx = np.array([2, 3])

In [24]: m[idx]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-a52866a6fec6> in <module>()
----> 1 m[idx]

TypeError: only integer scalar arrays can be converted to a scalar index

如果将m转换为CSR矩阵,则可以使用idx对其进行索引:

In [25]: m.tocsr()[idx]
Out[25]: 
<2x4 sparse matrix of type '<class 'numpy.int64'>'
    with 2 stored elements in Compressed Sparse Row format>

如果要进行更多索引,最好将新数组保存在变量中,并根据需要使用它:

In [26]: a = m.tocsr()

In [27]: a[idx]
Out[27]: 
<2x4 sparse matrix of type '<class 'numpy.int64'>'
    with 2 stored elements in Compressed Sparse Row format>

In [28]: a[0,0]
Out[28]: 0

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

Python:同时在for循环中添加到列表列表 - python

我想用for循环外的0索引值创建一个新列表,然后使用for循环添加到相同的列表。我的玩具示例是:import random data = ['t1', 't2', 't3'] masterlist = [['col1', 'animal1', 'an…

查找字符串中的行数 - python

我正在创建一个python电影播放器​​/制作器,我想在多行字符串中找到行数。我想知道是否有任何内置函数或可以编写代码的函数来做到这一点:x = """ line1 line2 """ getLines(x) python大神给出的解决方案 如果换行符是'\n',则nlines …