简体   繁体   中英

concatenate a customized format of a sparse matrix X with a target array Y in Python

I have a sparse matrix X and a target array Y (which length is equal to the rows of X), imagine something like following :

 X=([1.5 0.0 0.0 71.9 0.0 0.0 0.0], 
    [0.0 10.0 0.0 2.0 0.0 0.0 0.0], 
    [0.0 0.0 0.0 0.0 0.0 0.0 11.0])

 y =[4,2,-6]

what I need is to first have new form of the sparse matrix where each row contain nonzero values and their corresponding indices of rows in X :

Example

X1=( 0:1.5 3:71.9
     1:10 3:2
     6:11 )

to do so I have already asked this question (however I still don't know how to store X1 there so that later I concatenate it with Y?) but second part of the question is to concatenate X1 and Y (number of rows in X1 is still equal to length of Y) and store the final result , the final result should be something like the following format:

  data:
       4 0:1.5 3:71.9
       2 1:10 3:2
      -6 6:11
       ... 

what is the way to get from X,Y into the final data and store it in a text file in Python?

Concatenate like so:

data = [[a]+b for a, b in zip(Y, X1)]  
# data = [[a]+b for a, b in zip(Y, [':'.join([k,v]) for k,v in X1.items()])]

and write to file:

with open(filename, 'w') as f:
    for row in data:
        f.write(' '.join(row))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM