Applying a custom function to a column in a dataframe

Viewed 36

I have a custom function that takes in a 8-character identifier (CUSIP), and based on some logic generates the 9th character (check bit). I want to apply this function to a dataframe consisting of 8-char identifiers and return back the dataframe with the full 9-char string.

e.g. a list of 2 8-char cusips:

list1 = [[ '912810SE',
'912810SF']]

pd1 = pd.DataFrame(list1)

print(pd1.apply(gen_cusip_checkbit))

I am expecting 9 and 6; however, I am getting 4 and 2 when applying the function to the df. Also, this should loop 8 times in the function, but when applied to the df it loops 36 times.

This is the function:

def gen_cusip_checkbit(cusip):
    cusip=str(cusip).upper()
    sumnum = 0
    for i in range(len(cusip)):
        val = 0
        if cusip[i].isnumeric():
            val = int(cusip[i])
        else:
            val = int(cusip_alpha.find(cusip[i])+10)  # refers to alphabet string for mapping
        if i % 2 != 0:
            val *= 2
        val = (val % 10) + (val // 10)   
        sumnum += val
    return str((10 - (sumnum % 10)) % 10)
1 Answers

so it looks like when you do :

pd1.apply(gen_cusip_checkbit)

The variable sent to the function consists of :

0    912810SE
NAME: 0, DTYPE: OBJECT

The length of this variable is 36 which answers why your loop has 36 iterations

If you run the apply function against the column :

pd1[0].apply(gen_cusip_checkbit)

The variable that would be sent is just :

912810SE

which should give you the right output .

Related