使用字典替换pandas数据帧中的字符串而不重写

2024-06-26 04:59:10 发布

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

我试图转换一个pandas数据帧,其中的列填充了如下值:

df['Alteration']

Q79K,E17K
Q79K,E17K
T315I

并希望将单字母氨基酸转换为三字母代码,看起来更像:

^{pr2}$

到目前为止,我尝试使用一个使用regex表达式作为键的字典,例如:

AA_code = {re.compile('[C]'): 'Cys',re.compile('[D]'): 'Asp', 
re.compile('[S]'): 'Ser',re.compile('[Q]'): 'Gln',re.compile('[K]'): 'Lys', 
re.compile('[I]'): 'Ile',re.compile('[P]'): 'Pro',re.compile('[T]'): 'Thr', 
re.compile('[F]'): 'Phe',re.compile('[N]'): 'Asn',re.compile('[G]'): 'Gly', 
re.compile('[H]'): 'His',re.compile('[L]'): 'Leu',re.compile('[R]'): 'Arg', 
re.compile('[W]'): 'Trp',re.compile('[A]'): 'Ala',re.compile('[V]'): 'Val', 
re.compile('[E]'): 'Glu',re.compile('[Y]'): 'Tyr',re.compile('[M]'): 'Met'}

并根据字典替换以下代码:

df['Replacement'] = dfx2['Alteration'].replace(AA_code, regex=True)

但是,我得到了一些奇怪的行为,其中replace函数重写了值,看起来更像这样:

Glyln79Leuys,Glu17Leuys
Glyln79Leuys,Glu17Leuys
Thr315Ile

据我所知,Glyln是从代码中派生出来的,它首先将Q改为Gln,然后用字典中的G:Gly key:value对重写Glyln。有没有办法解决这个问题??在

谢谢你!!在


Tags: 代码redf字典字母codereplaceregex
2条回答

乔恩的回答很好。根据他的意见,另一种方法是

import pandas as pd

lookup = {
    'Q': 'Gln',
    'K': 'Lys',
    'E': 'Glu',
    'G': 'Gly'
     # needs completing...
}

s = pd.Series(['Q79K,E17K', 'Q79K,E17K', 'T315I'])
s.apply(lambda row: "".join([lookup[x] if x in lookup else x for x in row]))

或者,正如@Jon Clements在评论中建议的那样

s.apply(lambda row: "".join([lookup.get(x,x) for x in row]))

这给了你

^{pr2}$

创建一个查找表,然后在Series.str.replace中的可调用中使用它,例如:

import pandas as pd

lookup = {
    'Q': 'Gln',
    'K': 'Lys',
    'E': 'Glu',
    'G': 'Gly'
    # needs completing...
}

s = pd.Series(['Q79K,E17K', 'Q79K,E17K', 'T315I'])
s.str.replace('([{}])'.format(''.join(lookup)), lambda m: lookup[m.group(1)])

给你:

^{pr2}$

相关问题 更多 >