在Python中,选择特定列只能形成一个数据帧

2024-05-12 19:17:49 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python和pandas作为pd,我试图输出一个文件,该文件具有基于特定头的列子集。

下面是一个输入文件的示例

gene_input = pd.read_table(args.gene, sep="\t" ,index_col=0)

基因输入的结构:

       Sample1  Sample2  Sample3  Sample4  Sample5  Sample6  Sample7  Sample8
Gene1        2       23      213      213       13      132      213     4312
Gene2        3       12    21312      123      123       23     4321      432
Gene3        5      213    21312       15      516     3421     4312     4132
Gene4        2      123      123        7      610       23     3214     4312
Gene5        1      213      213        1      152       23     1423     3421

使用不同的循环,我生成了两个字典。第一个有键(示例1和示例7),第二个有键(示例4和8)。

我希望有以下输出(请注意,我希望每个词典中的示例是连续的;即先是所有词典1,然后是所有词典2): 我要的输出是:

        Sample1 Sample7 Sample4 Sample8
Gene1   2   213 213 4312
Gene2   3   4321    123 432
Gene3   5   4312    15  4132
Gene4   2   3214    7   4312
Gene5   1   1423    1   3421

我试过以下方法,但没有成功:

key_num=list(dictionary1.keys())
num = genes_input[gene_input.columns.isin(key_num)]

为了提取第一组列,然后以某种方式组合它,但是失败了。它一直给我属性错误,我确实更新了熊猫。我还尝试了以下方法:

reader = csv.reader( open(gene_input, 'rU'), delimiter='\t')
header_row = reader.next() # Gets the header

for key, value in numerator.items():
    output.write(key + "\t")
    if key in header_row:
        for row in reader:
            idx=header_row.index(key)
            output.write(idx +"\t")

以及其他一些命令/循环/行。有时我只得到输出中的第一个键,有时我得到一个错误;这取决于我尝试的方法(为了方便起见,我没有将它们全部列在这里)。

无论如何,如果有人对我如何生成感兴趣的输出文件有任何意见,我将不胜感激。

同样,这里是我想要的最终输出:

        Sample1 Sample7 Sample4 Sample8
Gene1   2   213 213 4312
Gene2   3   4321    123 432
Gene3   5   4312    15  4132
Gene4   2   3214    7   4312
Gene5   1   1423    1   3421

Tags: 文件key示例inputreaderrowheadergene