How do you edit cells in a sparse matrix using scipy?

2024/10/6 22:33:21

I'm trying to manipulate some data in a sparse matrix. Once I've created one, how do I add / alter / update values in it? This seems very basic, but I can't find it in the documentation for the sparse matrix classes, or on the web. I think I'm missing something crucial.

This is my failed attempt to do so the same way I would a normal array.

>>> from scipy.sparse import bsr_matrix
>>> A = bsr_matrix((10,10))
>>> A[5][7] = 6Traceback (most recent call last):File "<pyshell#11>", line 1, in <module>A[5][7] = 6File "C:\Python27\lib\site-packages\scipy\sparse\bsr.py", line 296, in __getitem__raise NotImplementedError
NotImplementedError
Answer

There several Sparse matrix formats. Some are better suited to indexing. One that has implemented it is lil_matrix.

Al = A.tolil()
Al[5,7] = 6  # the normal 2d matrix indexing notation
print Al
print Al.A # aka Al.todense()
A1 = Al.tobsr()  # if it must be in bsr format

The documentation for each format suggests what it is good at, and where it is bad. But it does not have a neat list of which ones have which operations defined.

Advantages of the LIL formatsupports flexible slicingchanges to the matrix sparsity structure are efficient...
Intended UsageLIL is a convenient format for constructing sparse matrices...

dok_matrix also implements indexing.

The underlying data structure for coo_matrix is easy to understand. It is essentially the parameters for coo_matrix((data, (i, j)), [shape=(M, N)]) definition. To create the same matrix you could use:

sparse.coo_matrix(([6],([5],[7])), shape=(10,10))

If you have more assignments, build larger data, i, j lists (or 1d arrays), and when complete construct the sparse matrix.

https://en.xdnf.cn/q/70317.html

Related Q&A

AttributeError: DataFrame object has no attribute _data

Azure Databricks execution error while parallelizing on pandas dataframe. The code is able to create RDD but breaks at the time of performing .collect() setup: import pandas as pd # initialize list of …

Python: Problem with overloaded constructors

WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!I have written the following code, however I get the following exception: Message FileName Li…

Validate inlines before saving model

Lets say I have these two models:class Distribution(models.Model):name = models.CharField(max_length=32)class Component(models.Model):distribution = models.ForeignKey(Distribution)percentage = models.I…

Grouping and comparing groups using pandas

I have data that looks like:Identifier Category1 Category2 Category3 Category4 Category5 1000 foo bat 678 a.x ld 1000 foo bat 78 l.o …

Transform a 3-column dataframe into a matrix

I have a dataframe df, for example:A = [["John", "Sunday", 6], ["John", "Monday", 3], ["John", "Tuesday", 2], ["Mary", "Sunday…

python multiline regex

Im having an issue compiling the correct regular expression for a multiline match. Can someone point out what Im doing wrong. Im looping through a basic dhcpd.conf file with hundreds of entries such as…

OpenCV Python Bindings for GrabCut Algorithm

Ive been trying to use the OpenCV implementation of the grab cut method via the Python bindings. I have tried using the version in both cv and cv2 but I am having trouble finding out the correct param…

showing an image with Graphics View widget

Im new to qt designer and python. I want to created a simple project that I should display an image. I used "Graphics View" widget and I named it "graphicsView". I wrote these funct…

TemplateSyntaxError: settings_tags is not a valid tag library

i got this error when i try to run this test case: WHICH IS written in tests.py of my django application:def test_accounts_register( self ):self.url = http://royalflag.com.pk/accounts/register/self.c =…

Setting NLTK with Stanford NLP (both StanfordNERTagger and StanfordPOSTagger) for Spanish

The NLTK documentation is rather poor in this integration. The steps I followed were:Download http://nlp.stanford.edu/software/stanford-postagger-full-2015-04-20.zip to /home/me/stanford Download http:…