How to use pandas apply method, in case you need a parameterized function

  apply, pandas, parameters, python, replace

Input:

0      1     2
TNN    R11W  MSLQEMFRFPRGLLLGSVLLVASAPATL
ASTN1  E5V   MALAALCALLACCWGPAAVLATAAGDVDPSK
HSPB7  H19P  MSHRTSSTFRAERSFHSSHSSSSSSTSSSASRALPAQDPPMEK
CLCNKB C3Y   MECFVGLREGSSGNPVTLQELWGPCPRIRRGIRG
SZRD1  P10L  MEDEEVAESWEEAADSGEIDRRLEKKL

Expected output:

0      1     2
TNN    R11W  MSLQEMFRFPWGLLLGSVLLVASAPATL
ASTN1  E5V   NaN
HSPB7  H19P  MSHRTSSTFRAERSFHSSPSSSSSSTSSSASRALPAQDPPMEK
CLCNKB C3Y   MEYFVGLREGSSGNPVTLQELWGPCPRIRRGIRG
SZRD1  P10L  NaN

Code: examples

import pandas as pd
import sys

with open(file1, 'r') as mvf:
    lines_1 = [line.rstrip('n').split(',') for line in mvf]

df = pd.DataFrame(lines_1)

class CharacterReplacer:
    def __init__(self,varcolname=df[1], textcolname=df[2]):
        self.varcolname=varcolname
        self.textcolname=textcolname

    def text_replacer_informed_from_variant_column(self,row):
        variant_desc=row[self.varcolname]
        c, p, r =  (variant_desc[0], int(variant_desc[1:-1]), variant_desc[-1])
        row[self.textcolname]=CharacterReplacer.replace_a_char_in_a_pos(row[self.textcolname], c, p, r)
        return row

    @staticmethod
    def replace_a_char_in_a_pos(target_seq, pos, fromchar, tochar):
        pos=pos-1
        if( target_seq[pos]!=fromchar ):
            sys.stderr.write("{} does not match with {}".format(target_seq[pos],fromchar))

        out_seq= target_seq[:pos]+  tochar + target_seq[pos+1:]
        return out_seq

charreplacer=CharacterReplacer(df[1],df[2])
df_new = df.apply(charreplacer.text_replacer_informed_from_variant_column, axis=1)

I wanna change a character in ‘column 2’ with the index of ‘column 1’. For example, in first row, if I check the index of ‘column 1’, I will fine ‘R’ in 11th character of ‘column 2’. If the character is ‘R’, I wanna change it as ‘W’. If not, I wanna write ‘NaN’ in the cell. How can I replace a character of ‘column2’ with the information of ‘column1’.

Source: Python Questions

LEAVE A COMMENT