如何基于其他列的多个突发事件转换列?

时间:2019-12-21 03:24:48

标签: python pandas

我有一个数据框:

df = pd.DataFrame({'REF':list('GCTT'), 'ALT':list('AACG'),
                   'A1':['0/1','0/1','0/0','0/1'],
                   'A2':['1/1','0/1','0/1','0/0']})
  REF ALT   A1   A2
0   G   A  0/1  1/1
1   C   A  0/1  0/1
2   T   C  0/0  0/1
3   T   G  0/1  0/0

我想基于REF和ALT列中的值转换列A1和A2。因此,第0行的A1和A2列应显示GA和AA。例如,丢失“ /”,将0替换为G,将1替换为A。接下来,第1行应将C替换为0,将A替换为1。然后按照下一行的模式进行操作:

  REF ALT  A1   A2
0   G   A  GA  AA
1   C   A  CA  CA
2   T   C  TT  TC
3   T   G  TG  TT

在我的数据中,有数百个A列:A1,A2 ...... An-1,An。因此,该解决方案需要在所有列中都是可复制的。

3 个答案:

答案 0 :(得分:2)

I wonder how fast this solution is with your data:

for col in ["A1","A2"]: 
        df[col]= df[col].str.split("/",expand=True) \
                        .replace(["0","1"],[df.REF,df.ALT]) \
                        .agg("".join,axis=1) 

df                                                                                                                  

  REF ALT  A1  A2
0   G   A  GA  AA
1   C   A  CA  CA
2   T   C  TT  TC
3   T   G  TG  TT

编辑:解决方案2.,使用索引:

# helper structs:
ncbscols= ["REF","ALT"]
cols= df.columns.difference(ncbscols)

ii= pd.MultiIndex.from_product([list("ACGT"),list("ACGT"),["0/0","0/1","1/1","1/0"] ])
ser= pd.Series( [t[2].replace("/","").replace("0",t[0]).replace("1",t[1]) for t in ii ],  index=ii )

# the main calculation:
for c in cols:
    mi= pd.MultiIndex.from_arrays([ df.REF.values,df.ALT.values,df[c].values ])
    df[c]= ser[mi].values


ser:
 A  A  0/0    AA
      0/1    AA
      1/1    AA
      1/0    AA
   C  0/0    AA
             ..
T  G  1/0    GT
   T  0/0    TT
      0/1    TT
      1/1    TT
      1/0    TT
Length: 64, dtype: object 

df:
  REF ALT  A1  A2
0   G   A  GA  AA
1   C   A  CA  CA
2   T   C  TT  TC
3   T   G  TG  TT

答案 1 :(得分:0)

我认为可能会有更好的方法来做到这一点,但这是可行的。 让我知道这是否是性能问题。

XDO_

另一个选择

acols = df.drop(['REF', 'ALT'], axis=1).columns

for i in acols:
    df.loc[df[i] == '0/0', i] = df['REF'] * 2
    df.loc[df[i] == '0/1', i] = df['REF'] + df['ALT']
    df.loc[df[i] == '1/1', i] = df['ALT'] * 2
for i in acols:
    df[i] = df[i].replace(to_replace='0/0', value=df['REF']+df['REF'])
    df[i] = df[i].replace(to_replace='0/1', value=df['REF']+df['ALT'])
    df[i] = df[i].replace(to_replace='1/1', value=df['ALT']+df['ALT'])

答案 2 :(得分:0)

您只有4个01组合,所以我认为您可以尝试np.select

df1 = df.drop(['REF', 'ALT'], axis=1)

#conditions
combo = ['0/0', '0/1', '1/0', '1/1']
conds = [df1.eq(x) for x in combo]

#selections
s00 = (df.REF * 2).to_numpy()[:,None]
s11 = (df.ALT * 2).to_numpy()[:,None]
s01 = (df.REF + df.ALT).to_numpy()[:,None]

df.loc[:, df1.columns.tolist()] = np.select(conds , [s00, s01, s01[:,::-1], s11], np.nan)

Out[260]:
  REF ALT  A1  A2
0   G   A  GA  AA
1   C   A  CA  CA
2   T   C  TT  TC
3   T   G  TG  TT