Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using oop for dataframes

I want to refactor my code and trying to creating OOP set up for basic dataframe manipulations.
This might not make sense in a larger context but I am trying to get a better grasp on OOP.
I have tried a rename column function but it does not work on my created instance(m1).

df1 = pd.read_sql(query, conn)
class DataframeOperations():
    def __init__(self, df):
    self.df = df

    def rename_column(self, name:'string', name_adj:'string'):
        self.df.rename(columns = {name, name_adj}, inplace=True)
        return self.df

m1 = DataframeOperations(df1)
print(type(m1))

output untill this point

<class ‘main.DataframeOperations’>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

m1.rename_column('col1','col2')

I get the following error when running this function:

TypeError: ‘set’ object is not callable

>Solution :

in columns you are defining a set instead of a dictionary, try this:

df1 = pd.DataFrame({'a':[1,3,4]})

class DataframeOperations():
    def __init__(self, df):
        self.df = df

    def rename_column(self, name:'string', name_adj:'string'):
        replace_dict = {name: name_adj}
        self.df.rename(columns =replace_dict , inplace=True)
        return self.df

m1 = DataframeOperations(df1)
print(type(m1))

m1.rename_column('a','b')

But in general and in special for OOP, what you want is that DataframeOperations inherits from pd.DataFrame:

class DataframeOperations(pd.DataFrame):

    def rename_column(self, name:'string', name_adj:'string'):
        replace_dict = {name: name_adj}
        self.rename(columns =replace_dict , inplace=True)
        return self

df1 = DataframeOperations({'a':[1,3,4]})
df1.rename_column('a','b')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading