Python Pandas:如果列表中的项目与pandas中的列行匹配,请添加新列

时间:2019-06-20 18:59:01

标签: python pandas

我有一个pandas数据框和一个列表列表(每个子列表都有3个项[name,seq,qual])。我想检查列表列表中的第一项是否与df的名称列匹配,如果要匹配,我想创建将item [1]和item [2]添加到数据框中的新列。

要设置它:

reads = [['read1', 'ACTG', 'FFFF'], ['read2', 'TTTT', 'FF:F'], ['read3', 'ATGC', 'F:FF']]
df = pd.DataFrame(reads, columns=['ReadName', 'Sequence1', 'Qual1'])
reads2 = [['read3', 'CGCG', 'F::F'], ['read1', 'TGTG', 'F:FF'], ['read2', 'AAAA', 'FFFF']]

我尝试过的事情:

for item in reads2:
    if item[0] in df['ReadName']:
        df['Sequence2'] = item[1]
        df['Qual2'] = item[2]

但是生成的df看起来像:

  ReadName Sequence1 Qual1 Sequence2 Qual2
0    read1      ACTG  FFFF      CGCG  F::F
1    read2      TTTT  FF:F      CGCG  F::F
2    read3      ATGC  F:FF      CGCG  F::F

因此,它仅将列表列表中的第一项添加到df中的所有行。我希望它看起来像:

  ReadName Sequence1 Qual1 Sequence2 Qual2
0    read1      ACTG  FFFF      TGTG  F:FF
1    read2      TTTT  FF:F      AAAA  FFFF
2    read3      ATGC  F:FF      CGCG  F::F

2 个答案:

答案 0 :(得分:1)

使用.loc更新行

for item in reads2:

    if item[0] in list(df['ReadName']):

        df.loc[df['ReadName']==item[0],'Sequence2'] = item[1]
        df.loc[df['ReadName']==item[0],'Qual2'] = item[2]

答案 1 :(得分:1)

使用左联接:

df2 = pd.DataFrame(reads2, columns = ['ReadName', 'Sequence2', 'Qual2'])
df.merge(df2, on='ReadName')

看起来像:

    ReadName    Sequence1   Qual1   Sequence2   Qual2
0   read1   ACTG    FFFF    TGTG    F:FF
1   read2   TTTT    FF:F    AAAA    FFFF
2   read3   ATGC    F:FF    CGCG    F::F