Skip to content

Commit 8be15b2

Browse files
committed
Added to_coo method to SparseVector
1 parent f36aa11 commit 8be15b2

2 files changed

Lines changed: 9 additions & 0 deletions

File tree

pgvector/utils/sparsevec.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,12 @@ def dim(self):
5252
def to_dict(self):
5353
return dict(zip(self._indices, self._values))
5454

55+
def to_coo(self):
56+
from scipy.sparse import coo_array
57+
58+
coords = ([0] * len(self._indices), self._indices)
59+
return coo_array((self._values, coords), shape=(1, self._dim))
60+
5561
def to_list(self):
5662
vec = [0.0] * self._dim
5763
for i, v in zip(self._indices, self._values):

tests/test_sparse_vector.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,6 @@ def test_dim(self):
2727

2828
def test_to_dict(self):
2929
assert SparseVector.from_dense([1, 0, 2, 0, 3, 0]).to_dict() == {0: 1, 2: 2, 4: 3}
30+
31+
def test_to_coo(self):
32+
assert SparseVector.from_dense([1, 0, 2, 0, 3, 0]).to_coo().toarray().tolist() == [[1, 0, 2, 0, 3, 0]]

0 commit comments

Comments
 (0)