1

I have a class where one of the attributes is a pandas dateframe.

class AthletesJsonReader(object):
    def __init__(self, df=None, # A lot of other irrelevant attributes )
    self.df = df

And a method that's writing it.

    def pd_table(self):
        d = {'Name': self.names, 'PTS': self.pts, 'REB': self.reb, 'AST': self.ast, 'STL': 
              self.stl,
             'BLK': self.blk, 'FGM': self.fgm, 'FGA': self.fga, 'FG%': self.fgp, '3PM': 
              self.three_pm,
             '3PA': self.three_attempted, '3P%': self.three_percent, 'FTM': self.ftm,
             'FTA': self.fta, 'FT%': self.percent_ft}
        self.df = pd.DataFrame(d)

when I'm trying to inherit self.df and use it in another subclass method, it's returns none and error.

    def __init__(self):
        draft.AthletesJsonReader.__init__(self)

    def get_player_stats(self):
        print(self.df)
        player_name = input("enter player's name: ")
        end_name = player_name.title()
        player_stats = self.df.loc[self.df.Name == '{}'.format(end_name)]
        print(player_stats)

output:

None
AttributeError: 'NoneType' object has no attribute 'loc'

I've looked up for info about what's happening here and didn't quite found a straightforward answer / or it just me not understanding them. for example:

How to subclass pandas DataFrame?

Subclassing a Pandas DataFrame, updates?

https://dev.to/pj_trainor/extending-the-pandas-dataframe-133l

1 Answers1

1

Your are inheriting the class, not the instance. When you create the subclass instance, self.df is initialized to None. You need to call self.pd_table() also in the child class somewhere (or in the parent __init__, since that's called by the child initializer anyway).

For example, if you have other ways of creating self.df, but you want to make sure it's there when you need it, you could do:

    def get_player_stats(self): 
        if not self.df:
            self.pd_table()
        print(self.df)

Note: This has nothing to do with "subclassing pandas DataFrame". This would be relevant if you tried to do something like class MyClass(pd.DataFrame):

mcsoini
  • 6,280
  • 2
  • 15
  • 38