Apply a condition where Boolean is True and another condition where boolean is False

Question:

I have a function inside a class that accepts a dataframe and a function that accepts a dataframe column.

import pandas as pd
import numpy as np

class ChangeDateRange():

    def __init__(self, dataframe):
        self.dataframe = dataframe

      def abc_ab(self, col):

        if (self.dataframe[col].str[:3] == 'ABC') is True:
            return ('AB ' + self.dataframe[col].str[7:])
        elif (self.dataframe[col].str[:2] == 'AB') is True:
            return ('ABC' + self.dataframe[col].str[3:]
        else:
            return 1

For eg. Dataframe column values are

ABC 3432334534543
AB 5545345434

When I import this class using the below I get the output as 1 even though I have instances in the pandas column that meet both if and elif conditions.

dt_range = dt_range.ChangeDateRange(df)
dt_range.abc_ab(col= 'key')

How can I write a function within a class that accepts a dataframe column and applies a condition based on whether the bool is True or False?

I can do this outside of a class like below, however is there is a solution that works inside a class?

def abc_ab(row):
    abcd = row['key']

    if abcd[:3] =='TBK':
        return 'AB '+ abcd[7:]
    elif abcd[2:] == 'TB':
        return 'ABC' + abcd[3:]
        
df.apply(abc_ab, axis=1)
Asked By: R Sta

||

Answers:

ChatGPT gave me the correct answer –

import pandas as pd

class DataframeModifier:
    def __init__(self, dataframe):
        self.df = dataframe

    def modify_account_column(self,col):
        self.df[col] = self.df[col].apply(lambda x: x[-3:] if x.startswith('ABC') else x[-2:] if x.startswith('AB') else x)

list_ = ['ABC::1234545432', 'AB23423432']
df = pd.DataFrame(data = list_, columns = ['Account'])
modifier = DataframeModifier(df)
modifier.modify_account_column('Account')
print(df)
Answered By: R Sta
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.