如何在python中将链接列表转换为矩阵

时间:2015-09-18 09:00:37

标签: python matrix

我的输入数据看起来像(input.txt):

AGAP2     TCGA-BL-A0C8-01A-11R-A10U-07      66.7328
AGAP2     TCGA-BL-A13I-01A-11R-A13Y-07      186.8366
AGAP3     TCGA-BL-A13J-01A-11R-A10U-07      183.3767
AGAP3     TCGA-BL-A3JM-01A-12R-A21D-07      33.2927
AGAP3     TCGA-BT-A0S7-01A-11R-A10U-07      57.9040
AGAP3     TCGA-BT-A0YX-01A-11R-A10U-07      99.8540
AGAP4     TCGA-BT-A20J-01A-11R-A14Y-07      88.8278
AGAP4     TCGA-BT-A20N-01A-11R-A14Y-07      129.7021

我希望output.txt看起来像:

        TCGA-BL-A0C8-01A-11R-A10U-07  TCGA-BL-A13I-01A-11R-A13Y-07  ...
AGAP2   66.7328                       186.8366
AGAP3   0                             0

1 个答案:

答案 0 :(得分:0)

使用pandas:读取csv,创建pivot并编写csv。

import pandas as pd

df = pd.read_table("input.txt", names="xy", sep=r'\s+')
# reset index first - we need named column
new = df.reset_index().pivot(index="index", columns='x', values='y')
new.fillna(0, inplace=True)
new.to_csv("output.csv", sep='\t')      # tab separated

result

Reshaping and Pivot Tables

编辑:填空值

相关问题