What Is The Use Case Of Numpy Array Of Scalar Value?
Solution 1:
You've created a sparse matrix, shape (3,4), but no elements:
In [220]: a = sparse.csr_matrix((3, 4), dtype=np.int8)
In [221]: a
Out[221]:
<3x4 sparse matrix of type'<class 'numpy.int8'>'
with 0 stored elements in Compressed Sparse Row format>
In [222]: a.toarray()
Out[222]:
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
Selecting one element:
In[223]: a[0,0]Out[223]: array(0, dtype=int8)
Converting it to a dense np.matrix
:
In[224]: a.todense()
Out[224]:
matrix([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
In[225]: a.todense()[0,0]Out[225]: 0
and to other sparse formats:
In[226]: a.tolil()[0,0]Out[226]: 0In[227]: a.todok()[0,0]Out[227]: 0
It looks like csr
is some what unique in returning a scalar array like this. I'm not sure if it's intentional, a feature, or a bug. I haven't noticed it before. Usually we work with the whole matrix, rather than specific elements.
But a 0d array is allowed, even if in most cases it isn't useful. If we can have 2d or 1d arrays, why not 0?
There are a couple of ways of extracting that element from a 0d array:
In[233]: np.array(0, 'int8')
Out[233]: array(0, dtype=int8)
In[234]: _.shapeOut[234]: ()
In[235]: __.item()
Out[235]: 0In[236]: ___[()] # indexwithanemptytupleOut[236]: 0
Scipy version 1.3.0 release notes includes:
CSR and CSC sparse matrix fancy indexing performance has been improved substantially
https://github.com/scipy/scipy/pull/7827 - looks like this pull request was a long time in coming, and had a lot of faults (and may still). If this behavior is a change from previous scipy releases, we need to see if there's a related issue (and possibly create one).
https://github.com/scipy/scipy/pull/10207 BUG: Compressed matrix indexing should return a scalar
Looks like it will be fixed in 1.4.
Solution 2:
What are they?
They're seemingly an single-element array, like an array with one element.
How do I get the value out of it?
By using:
>>>np.array(0).item()
0
>>>
Post a Comment for "What Is The Use Case Of Numpy Array Of Scalar Value?"