pairwise comparison within a column pandas python Biopython
Question: i have a large data set that i read in with pandas and i want to do pairwise
alignment by pairwise2.

    
    
    import pandas as pd
    from pandas import DataFrame
    from Bio import pairwise2   #for pairwise alignments 
    from Bio.pairwise2 import format_alignment   #for printing alignments out neatly 
    

but here i will use a mock data set:

    
    
    data = { 'sequence': ['ACAAGAGTGGGACTATACAGTGGGTACAGTTATGACTTC', 'GCACGGGCCCTTGGCTAC', 'GCAACAAGGGGGGATACAGCGGGAACAGTGGACAAGTGGTTCGATGTC']}
    
    data = DataFrame(data)
    

look like this:

    
    
    Out[34]: 
                                           sequence
    0           ACAAGAGTGGGACTATACAGTGGGTACAGTTATGACTTC
    1                                GCACGGGCCCTTGGCTAC
    2  GCAACAAGGGGGGATACAGCGGGAACAGTGGACAAGTGGTTCGATGTC
    

my goal is to do a pairwise alignment within the 'sequence' column, so the
first row compares with the second, then the second compares with the third,
the third compares with the first, and so on for a larger data set.

my code :

    
    
    for seq in data['sequence']:
       for a in pairwise2.align.globalxx(seq, seq):
          print(format_alignment(*a))   #this is just to print the alignment out neatly. 
    

this prints out:

    
    
    ACAAGAGTGGGACTATACAGTGGGTACAGTTATGACTTC
    |||||||||||||||||||||||||||||||||||||||
    ACAAGAGTGGGACTATACAGTGGGTACAGTTATGACTTC
    Score=39
    
    GCACGGGCCCTTGGCTAC
    ||||||||||||||||||
    GCACGGGCCCTTGGCTAC
    Score=18
    
    GCAACAAGGGGGGATACAGCGGGAACAGTGGACAAGTGGTTCGATGTC
    ||||||||||||||||||||||||||||||||||||||||||||||||
    GCAACAAGGGGGGATACAGCGGGAACAGTGGACAAGTGGTTCGATGTC
    Score=48
    

which is close to what i want but it only compares the first to the first,
second to second and third to third.

so i tried this:

    
    
    for seq in data['sequence']: #for each 'sequence' column value
        for index, row in data.iterrows(): #for each row 
            for a in pairwise2.align.globalxx(seq, row['sequence']): #compare 'sequence' column value to each row of the 'sequence' column
                print(format_alignment(*a))
    

this gave out way too many lines of output i'm not even going to try to post
it here.

my idea was to compare the 'sequence' value to the rows of the 'sequence'
column, but the output gave way too many alignments than expected. i think the
double loop is not the way to go here. **i guess my question doesn't even have
anything to do with Biopython, just simply how can i do pairwise comparisons
within one column?**


Answer: Use the combinatoric generators from
[`itertools`](https://docs.python.org/2/library/itertools.html#itertools.combinations).

    
    
    for seq0, seq1 in itertools.combinations(data['sequence'], 2):
        for a in pairwise2.align.globalxx(seq0, seq1):
            print(format_alignment(*a))
    

