如何给Scipy的csr_matrix指定行和列的名称?

8
我不知道是否有可能,这可能是一个天真的问题,但我该如何设置与R中的rownames()colnames()相当的内容到一个scipy.sparse.csr.csr_matrix中呢?
我发现my_matrix.dtype.names在这里不起作用,而且我找不到任何针对这种稀疏矩阵的“索引”等效方法...
此外,由于一些未解决的问题,pandas.sparse.*不是一个选择...
非常感谢您的帮助。

dtype.names 指的是结构化数组中的 fields。可以将其视为 CSV 表格中的列名/表头。您无法在字段之间进行太多数学计算。而且您不能在稀疏矩阵中使用这种类型的 dtype - hpaulj
2个回答

11

由于scipy稀疏格式不支持命名索引,因此您需要单独维护名称。可能看起来像这样:

foo = csr_matrix(...)
row_names = np.array(...)
col_names = np.array(...)

# index by name:
row_idx, = np.where(row_names == "my row")
col_idx, = np.where(col_names == "my col")
foo[row_idx, col_idx]

我在想使用字典查找是否更快?稀疏的“dok”格式实际上是一个字典,索引元组作为键。 - hpaulj
效率取决于矩阵的大小和稀疏程度,但是,名称->索引的字典也可以使用。DOK格式不起作用,因为它的键必须是整数对。 - perimosocordiae
但他可以用标签元组作为键创建自己的字典。这不会给他任何数学能力。 - hpaulj

-1
请查看"SSparseMatrix"包。(该包使用SciPy的稀疏矩阵。)
以下是创建和行选择示例(在Python会话中):
>>> from SSparseMatrix import *
>>> mat = [[1, 0, 0, 3], [4, 0, 0, 5], [0, 3, 0, 5], [0, 0, 1, 0], [0, 0, 0, 5]]
>>> smat = SSparseMatrix(mat)
>>> smat.set_column_names(["a", "b", "c", "d"])
<5x4 SSparseMatrix (sparse matrix with named rows and columns) of type '<class 'numpy.int64'>'
    with 8 stored elements in Compressed Sparse Row format, and fill-in 0.4>
>>> smat.set_row_names(["A", "B", "C", "D", "E"])
<5x4 SSparseMatrix (sparse matrix with named rows and columns) of type '<class 'numpy.int64'>'
    with 8 stored elements in Compressed Sparse Row format, and fill-in 0.4>
>>> smat.print_matrix()
===================================
  |       a       b       c       d
-----------------------------------
A |       1       .       .       3
B |       4       .       .       5
C |       .       3       .       5
D |       .       .       1       .
E |       .       .       .       5
===================================
>>> smat[["A","B"],:].print_matrix()
===================================
  |       a       b       c       d
-----------------------------------
A |       1       .       .       3
B |       4       .       .       5
===================================

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接