【问题标题】:Match object in list of tuples to object in dataframe, create new column if match exists将元组列表中的对象与数据框中的对象匹配,如果匹配存在则创建新列
【发布时间】:2018-09-21 19:55:37
【问题描述】:

考虑以下元组列表:

some_strings = [('Name1', 'ABCD', 'DEFG', 'Score=12'),
                ('Name2', 'JKLL', 'RMPQ', 'Score=11')]

还有以下 pandas 数据框:

Sequence ID    Left Sequence    Right Sequence
Name1              ABCD             RQLM
Name1              ABCR             PLMT
Name2              JKLL             ZFGQ
Name2              RPLP             FTRD

我正在尝试将元组中的第二个对象与列 df['Left Sequence'] 进行比较,以检查是否完全匹配(不关心部分匹配),如果匹配发生,则在新列中打印二聚体在df的末尾。如果没有匹配,我将打印 NA。这是我尝试过的代码:

for x in some_strings:
    for y in x:
        df['Dimers'] = df['Left Sequence'].apply(lambda s: 'Dimer' if s == y[1] else 'NA')

我的预期输出:

Sequence ID    Left Sequence    Right Sequence    Dimers
Name1              ABCD             RQLM          Dimer
Name1              ABCR             PLMT           NA
Name2              JKLL             ZFGQ          Dimer
Name2              RPLP             FTRD           NA

我的实际输出(你可能猜到了):

Sequence ID    Left Sequence    Right Sequence    Dimers
Name1              ABCD             RQLM           NA
Name1              ABCR             PLMT           NA
Name2              JKLL             ZFGQ           NA
Name2              RPLP             FTRD           NA

任何建议都会很棒。

【问题讨论】:

    标签: python string pandas tuples


    【解决方案1】:

    创建布尔掩码:我们使用isin创建掩码

    mask=df.iloc[:,:-1].apply(tuple,1).isin([x[:-2] for x in some_strings])    
    df['Dimer']='NA'
    df.loc[mask,'Dimer']='Dimer'        
    df
    Out[1120]: 
      SequenceID LeftSequence RightSequence  Dimer
    0      Name1         ABCD          RQLM  Dimer
    1      Name1         ABCR          PLMT     NA
    2      Name2         JKLL          ZFGQ  Dimer
    3      Name2         RPLP          FTRD     NA
    

    【讨论】:

    • 谢谢,它适用于我的练习数据集,但是对于我的真实数据集,掩码返回 false,因此肯定存在一些潜在问题。感谢您的帮助!
    猜你喜欢
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多