menu

Questions & Answers

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

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)
Comments:
2023-01-19 00:30:04
The class makes absolutely no sense here
2023-01-19 00:30:04
Classes don't make transformations; they primarily maintain state. _change_date_range is already a "doing" name, which should just be a function. Also, classes should be named as ChangeDateRange according to PEP8 - you've basically just substituted a class for no apparent reason
2023-01-19 00:30:04
@roganjosh it's not the class doing the transformation, it's the function within the class.
2023-01-19 00:30:04
You've entirely missed my point
2023-01-19 00:30:04
Well then, I guess this is wrong ?stackoverflow.com/questions/40898482/…
2023-01-19 00:30:04
It's not even applicable to what you're doing
2023-01-19 00:30:04
2023-01-19 00:30:04
Had you not edited that last comment, I would have given up :) Let me see if I can give you a proper answer
2023-01-19 00:30:04
Answers(1) :

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)