简体   繁体   English

如何删除与Scipy稀疏矩阵的数字不同的元素?

[英]How to remove elements different than numbers of a Scipy Sparse Matrix?

I have a COO sparse matrix in which every element is a dictionary. 我有一个COO稀疏矩阵 ,其中每个元素都是一个字典。 I want to filter that matrix by some conditions, nevertheless when I try to multiply the matrix by the filter I get an exception TypeError: no supported conversion for types: (dtype('O'),) . 我想按某些条件过滤该矩阵,但是当我尝试将矩阵乘以过滤器时,出现异常TypeError: no supported conversion for types: (dtype('O'),) Is it possible to avoid this issue? 是否可以避免此问题?

from scipy.sparse import coo_matrix
import numpy as np

row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = [{"x": 1}, {"y": -1}, {"x": -1}, {"x": 2}, {"t": -2}, {"z": 2}]
matrix = coo_matrix((data, (row, col)), shape=(3, 3))

matrix.multiply(np.array([0, 1, 0])) # Raises exception

It is possible to filter a coo_matrix , nevertheless it isn't straightforward. 可以过滤coo_matrix ,但这并不简单。 First you must create your filter mask with `True/False' values and then use it to index the matrix's column, rows and data vectors. 首先,您必须使用“ True / False”值创建filter mask ,然后使用它对矩阵的列,行和数据向量进行索引。

In [22]: mask = [True, False, False, True, False, False]

In [23]: matrix.data[mask]
Out[23]: array([{'x': 1}, {'x': 2}], dtype=object)

In [24]: matrix.col[mask]
Out[24]: array([0, 0], dtype=int32)

In [25]: matrix.col[row]
Out[25]: array([0, 0, 2, 2, 2, 2], dtype=int32)

In [26]: matrix.col[mask]
Out[26]: array([0, 0], dtype=int32)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM