簡體   English   中英

將零的行和列插入 python 中的稀疏數組

[英]inserting rows and columns of zeros to a sparse array in python

我有 50ish 相對較大的稀疏 arrays(采用scipy.csr_array格式,但可以更改),我想在某些位置插入零行和零列。 密集格式的示例如下所示:

A = np.asarray([[1,2,1],[2,4,5],[2,1,6]])
# A = array([[1,2,1],
#            [2,4,5],
#            [2,1,6]])
indices = np.asarray([-1, -1, 2, -1, 4, -1, -1, 7, -1])

# indices =  array([-1, -1, 2, -1, 4, -1, -1, 7, -1])
#insert rows and colums of zeros where indices[i] == -1 to get B

B = np.asarray([[0,0,0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0,0,0],
                [0,0,1,0,2,0,0,1,0],
                [0,0,0,0,0,0,0,0,0],
                [0,0,2,0,4,0,0,5,0],
                [0,0,0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0,0,0],
                [0,0,2,0,1,0,0,6,0],
                [0,0,0,0,0,0,0,0,0]])

A是形狀為 (~2000, ~2000) 的稀疏數組,具有~20000 個非零條目, indices的形狀為 (4096, )。 我可以想象以密集格式進行操作,但我想我對數據和索引的存儲方式知之甚少,無法找到快速有效地對稀疏 arrays 執行此類操作的方法。

有人有什么想法或建議嗎?

謝謝。

您可以嘗試將非零值存儲在一個列表中,並將它們各自的索引存儲在另一個列表中:

data_list = [[], [], [1, 2, 1], [], [2, 4, 5], [], [], [2, 1, 6], []]
index_list = [[], [], [2, 4, 7], [], [2, 4, 7], [], [], [2, 4, 7], []]

這兩個列表只需要存儲每個非零值的數量,而不是一個包含 4,000,000 個值的列表。

如果您隨后想獲取 position (4, 7) 中的值:

def find_value(row, col):
    # Check to see if the given column is in our index list
    if col not in index_list[row]:
        return 0
    
    # Otherwise return the number in the data list
    myNum = data_list[row][index_list[row].index(col)]
    return myNum
    
find_value(4, 7)
output: 5

希望這可以幫助!

我可能會通過將數據和相關索引傳遞到 COO 矩陣構造函數來做到這一點:

import numpy as np
from scipy.sparse import coo_matrix

A = np.asarray([[1,2,1],[2,4,5],[2,1,6]])
indices = np.asarray([-1, -1, 2, -1, 4, -1, -1, 7, -1])

idx = indices[indices >= 0]
col, row = np.meshgrid(idx, idx)

mat = coo_matrix((A.ravel(), (row.ravel(), col.ravel())),
                 shape=(len(indices), len(indices)))
print(mat)
#   (2, 2)  1
#   (2, 4)  2
#   (2, 7)  1
#   (4, 2)  2
#   (4, 4)  4
#   (4, 7)  5
#   (7, 2)  2
#   (7, 4)  1
#   (7, 7)  6

print(mat.todense())
# [[0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0]
#  [0 0 1 0 2 0 0 1 0]
#  [0 0 0 0 0 0 0 0 0]
#  [0 0 2 0 4 0 0 5 0]
#  [0 0 0 0 0 0 0 0 0]
#  [0 0 0 0 0 0 0 0 0]
#  [0 0 2 0 1 0 0 6 0]
#  [0 0 0 0 0 0 0 0 0]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM