我确信这是一个比嵌套np.where语句更好的方法,但它应该在这个给定的例子中工作。
import pandas as pd
import numpy as np
# Create dummy data
code = pd.Series(['0:1', '1:0', '0:1', '0:.', '.:1', '0:1'])
ref = pd.Series(['A', 'G', 'A', 'T', 'A', 'T'])
alt = pd.Series(['a', 'b', 'c', 'd', 'e', 'f'])
df = pd.DataFrame()
虚拟数据输出:
code REF ALT
0 0:1 A a
1 1:0 G b
2 0:1 A c
3 0:. T d
4 .:1 A e
5 0:1 T f
嵌套np.where允许您检查两个以上的条件。
# Split the code string into two columns
df[['code_start', 'code_end']] = df['code'].str.split(':', expand=True)
# nested np.where to assign letters based on code for beginning of code column.
df['new_start'] = np.where(df['code_start']=='0', df['REF'], (np.where(df['code_start']=='1', df['ALT'], '0')))
# nested np.where to assign letters based on code for endof code column.
df['new_end'] = np.where(df['code_end']=='0', df['REF'], (np.where(df['code_end']=='1', df['ALT'], '0')))
# Create new code column combining columns as string.
df['new_code'] = df['new_start']+":"+df['new_end']
最终输出:
code REF ALT code_start code_end new_start new_end new_code
0 0:1 A a 0 1 A a A:a
1 1:0 G b 1 0 b G b:G
2 0:1 A c 0 1 A c A:c
3 0:. T d 0 . T 0 T:0
4 .:1 A e . 1 0 e 0:e
5 0:1 T f 0 1 T f T:f
从这里您可以删除额外的列。
我相信有一种更简洁的方法,也许使用re.sub但这是一种方法。