Home > Software design >  Class inheritance - how to modify a pandas DataFrame in a method
Class inheritance - how to modify a pandas DataFrame in a method

Time:10-23

The class myDataFrame inherits a pandas DataFrame. When I make modifications to the DataFrame using "self =", the operation completes successfully but in fact the DataFrame object is not modified. Why is this the case and what is the correct way to modify the DataFrame?

import pandas
class myDataFrame(pandas.DataFrame):
    def __init__(self, adict):
        super().__init__(adict)

    def df_reorder_columns(self):
        self = self[["Name", "Number"]] # this assignment doesn't work
        
my_data = {'Number': [1, 2],
           'Name': ['Adam', 'Abel']}

test_myDataFrame = myDataFrame(my_data)
print(test_myDataFrame)
test_myDataFrame.df_reorder_columns()
print(test_myDataFrame)
   Number  Name
0       1  Adam
1       2  Abel
   Number  Name
0       1  Adam
1       2  Abel

CodePudding user response:

import pandas
class myDataFrame(pandas.DataFrame):
    def __init__(self, adict):
        super().__init__(adict)

    def df_reorder_columns(self):
        self.__init__(self.loc[:, ["Name", "Number"]])
        

my_data = {'Number': [1, 2],
           'Name': ['Adam', 'Abel']}

test_myDataFrame = myDataFrame(my_data)
print(test_myDataFrame)

test_myDataFrame.df_reorder_columns()
print(test_myDataFrame)

Output:

   Number  Name
0       1  Adam
1       2  Abel


   Name  Number
0  Adam       1
1  Abel       2

CodePudding user response:

I think the dataframe object should be reinitilized with a desired order of columns

import pandas as pd     

class myDataFrame(pandas.DataFrame):

    def __init__(self, adict):
        super().__init__(adict)

    def df_reorder_columns(self):
        self.__init__({"Name": self.Name, "Number": self.Number})

my_data = {'Number': [1, 2],
           'Name': ['Adam', 'Abel']}

test_myDataFrame = myDataFrame(my_data)
print(test_myDataFrame)
test_myDataFrame.df_reorder_columns()
print(test_myDataFrame)
  • Related