votes up 1

row, column, and data array must all be the same length

Package:
scipy
github stars 8546
Exception Class:
ValueError

Raise code

oc__ = spmatrix.reshape.__doc__

    def getnnz(self, axis=None):
        if axis is None:
            nnz = len(self.data)
            if nnz != len(self.row) or nnz != len(self.col):
                raise ValueError('row, column, and data array must all be the '
                                 'same length')

            if self.data.ndim != 1 or self.row.ndim != 1 or \
                    self.col.ndim != 1:
                raise ValueError('row, column, and data arrays must be 1-D')

            return int(nnz)

        if axis

Ways to fix

votes up 1 votes down

scipy.sparse.coo_matrix expects row,column and data array to have the same length. If one of them disagrees in length this error is raised.

Steps to reproduce the error:

$ pipenv install scipy numpy

import numpy as  np
from scipy.sparse import coo_matrix
row  = np.array([0, 3, 1,]) # shorter length which causes an exception to be raised
col  = np.array([0, 3, 1, 2])
data = np.array([4, 5, 7, 9])
coo_matrix((data, (row, col)), shape=(4, 4)).toarray()

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-22-38fe1faad4df> in <module>()  4 col = np.array([0, 3, 1, 2])  5 data = np.array([4, 5, 7, 9]) ----> 6 coo_matrix((data, (row, col)), shape=(4, 4)).toarray() 
/usr/local/lib/python3.7/dist-packages/scipy/sparse/coo.py in __init__(self, arg1, shape, dtype, copy)  196 self.data = self.data.astype(dtype, copy=False)  197  --> 198 self._check()  199   200 def reshape(self, *args, **kwargs): 
/usr/local/lib/python3.7/dist-packages/scipy/sparse/coo.py in _check(self)  281 self.data = to_native(self.data)  282  --> 283 if self.nnz > 0:  284 if self.row.max() >= self.shape[0]:  285 raise ValueError('row index exceeds matrix dimensions') 
/usr/local/lib/python3.7/dist-packages/scipy/sparse/base.py in nnz(self)  248 count_nonzero : Number of non-zero entries  249 """ --> 250 return self.getnnz()  251   252 def getformat(self): 
/usr/local/lib/python3.7/dist-packages/scipy/sparse/coo.py in getnnz(self, axis)  243 nnz = len(self.data)  244 if nnz != len(self.row) or nnz != len(self.col): --> 245 raise ValueError('row, column, and data array must all be the '  246 'same length')  247  
ValueError: row, column, and data array must all be the same length

Fixed version:

import numpy as  np
from scipy.sparse import coo_matrix
row  = np.array([0, 3, 1, 0]) # here the same length as the rest of them
col  = np.array([0, 3, 1, 2])
data = np.array([4, 5, 7, 9])
coo_matrix((data, (row, col)), shape=(4, 4)).toarray()

array([[4, 0, 9, 0], 
       [0, 7, 0, 0], 
       [0, 0, 0, 0], 
       [0, 0, 0, 5]])

Oct 13, 2021 kellemnegasi answer
kellemnegasi 13.5k

Add a possible fix

Please authorize to post fix