根据条件在数据帧内的列之间交换多个数据帧的行

时间:2017-05-03 14:24:30

标签: python pandas numpy if-statement

我有一个如下所示的数据框,

foo = pd.DataFrame(
        [['chr1',2,1,'+',0.1,'NA','TSS1'],
        ['chr2',3,4,'-',0.03,'NA','TSS2'],
        ['chr3',7,6,'+',0.7,'NA','TSS3']], 
        columns = ('CHR', 'start', 'end','Strand','Peak','Ratio','Annotation')
    )
foo
    CHR start   end Strand  Peak    Ratio   Annotation
0   chr1    2   1   +   0.10    NA  TSS1
1   chr2    3   4   -   0.03    NA  TSS2
2   chr3    7   6   +   0.70    NA  TSS3

我的目标是在列的开始和结束之间进行交换,即如果列开始大于列结束,那么我需要它来交换它的位置并保持其余列完好无损或原样。

这样的事,

def fun(x):
   if df['start']> df['End']
print df[['CHR','end','start','Strand','Peak','Ratio','Annotation']]
   else
  return df

上述功能无法正常工作。 最后,我需要一个数据框,

    CHR   start  end    Strand  Peak    Ratio   Annotation
0   chr1    1   2   +   0.10    NA  TSS1
1   chr2    3   4   -   0.03    NA  TSS2
2   chr3    6   7   +   0.70    NA  TSS3

任何帮助或更好的建议都会很棒。另外,我有大量的多个数据帧。

1 个答案:

答案 0 :(得分:2)

我认为简化是:

foo[['start','end']] = foo[['start','end']].apply(np.sort, axis=1)
print (foo)
    CHR  start  end Strand  Peak Ratio Annotation
0  chr1      1    2      +  0.10    NA       TSS1
1  chr2      3    4      -  0.03    NA       TSS2
2  chr3      6    7      +  0.70    NA       TSS3

minmax的另一种解决方案:

df1 = foo[['start','end']]
foo['start'] = df1.min(axis=1)
foo['end'] =   df1.max(axis=1)
print (foo)
    CHR  start  end Strand  Peak Ratio Annotation
0  chr1      1    2      +  0.10    NA       TSS1
1  chr2      3    4      -  0.03    NA       TSS2
2  chr3      6    7      +  0.70    NA       TSS3

条件和numpy.where的解决方案,但需要numpy.column_stack才能为每列重复mask

b = foo['start'] < foo['end']
foo[['start','end']] = np.where(np.column_stack([b,b]),
                                foo[['start','end']],
                                foo[['end','start']])
print (foo)
    CHR  start  end Strand  Peak Ratio Annotation
0  chr1      1    2      +  0.10    NA       TSS1
1  chr2      3    4      -  0.03    NA       TSS2
2  chr3      6    7      +  0.70    NA       TSS3

如果不需要自定义函数apply

def fun(foo):
    b = foo['start'] < foo['end']
    foo[['start','end']] = np.where(np.column_stack([b,b]), 
                                    foo[['start','end']], 
                                    foo[['end','start']])
    return foo

print (fun(foo))
    CHR  start  end Strand  Peak Ratio Annotation
0  chr1      1    2      +  0.10    NA       TSS1
1  chr2      3    4      -  0.03    NA       TSS2
2  chr3      6    7      +  0.70    NA       TSS3