Extracting the CIGAR string from a BAM via Python? Is there a standard method in Python to extract a CIGAR string from the BAM?

There are great libraries which parse the CIGAR, e.g. https://pypi.python.org/pypi/cigar/0.1

&gt;&gt;&gt; c = Cigar('10M20S10M')
&gt;&gt;&gt; c.mask_left(10).cigar
'10S20S10M'
&gt;&gt;&gt; c.mask_left(9).cigar
'9S1M20S10M'
&gt;&gt;&gt; Cigar('10S').mask_left(10).cigar
'10S'
&gt;&gt;&gt; Cigar('10H').mask_left(10).cigar
'10H'
&gt;&gt;&gt; Cigar('10H').mask_left(11).cigar
'10H'
&gt;&gt;&gt; Cigar('10H').mask_left(9).cigar
'10H'


It looks like pysam already parses the cigar string, if I'm not mistaken:

import pysam

bam = 'myfile.bam'
bamfile = pysam.AlignmentFile(bam, 'rb')

for read in bamfile:
    if not read.is_unmapped:
        cigar = read.cigar
        print(cigar)


This outputs lists of tuples of the parse output:

[(5, 61), (0, 30), (5, 198)]
[(4, 11), (0, 30), (4, 248)]
[(4, 11), (0, 30), (4, 248)]
....


How could I simply output the CIGAR from read? I would prefer to create a column in a pandas DataFrame
If you really do just want the cigar string then it's read.cigarstring. However, I'm not sure what you're trying to gain with the cigar package from Brent. Unless you want to get the string with the masking changed then the tuple you get from pysam is the same as what you get from cigar (with the exception of the numeric operations instead of character operations).