连接一稀疏矩阵X的自定义格式与Python中的目标列Y [英] concatenate a customized format of a sparse matrix X with a target array Y in Python

查看:187
本文介绍了连接一稀疏矩阵X的自定义格式与Python中的目标列Y的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个稀疏矩阵X和一个目标列Y(其长度等于X的行),假设像以下

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]

我需要的是先有稀疏矩阵,其中的每行包含的非零值及其相应的指标行的新形式X:

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 :

示例

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

这样做,我已经问过这个<一个href=\"http://stackoverflow.com/questions/36388730/get-to-a-dictionary-format-by-just-saving-non-zero-values-and-indices-from-a-s\">question (不过,我还是不知道的如何存储X1 有这样以后我为Y串联吗?)但问题的第二部分是为连击X1和Y (在X1行数依然等于y的长度)和保存最终的结果,最后的结果应该是这样的格式如下:

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
       ... 

什么是的 X,Y ,以获得进入决赛的数据并存储在Python中的文本文件的方式?

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

推荐答案

串连像这样:

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()])]

和写入文件:

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

这篇关于连接一稀疏矩阵X的自定义格式与Python中的目标列Y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆