4

I'm trying to create a class which inherits a pandas DataFrame, with some modifications. However, it did not work as expected.

import pandas as pd
class result(pd.DataFrame):
    def __init__(self, x):
        pd.DataFrame.__init__(self)
        j = pd.DataFrame({'a': x})
        print(x)
        print(j)
        self.append(j)

The result:

>>> k = result([2,4])
[2, 4]
   a
0  2
1  4
>>> print(k)
Empty result
Columns: []
Index: []

As you can see, somehow the returned value is not appended by j. For comparison, observe when j and k are not defined within the class:

>>> k = pd.DataFrame()
>>> j = pd.DataFrame({'a': [2,4]})
>>> print(k.append(j))
   a
0  2
1  4

What causes the difference? What should I write within result if I want the arguments x to be appended into j?

Many thanks in advance!

Tim Mak
  • 297
  • 4
  • 10

1 Answers1

5

The reason is that append doesn't happen in-place, so you'll have to store the output. You can find an example in here enter link description here For in this case, you can do something like that:

import pandas as pd


class Result:

  def __init__(self):
      self.main_dataframe = pd.DataFrame(data=None, columns=['a'])

  def append_dataset(self, x):
      temp_dataframe = pd.DataFrame(data=x, columns=['a'])
      self.main_dataframe = self.main_dataframe.append(temp_dataframe)

  def debug(self):
      print(self.main_dataframe)
      # a
      # 0  2
      # 1  4


  if __name__ == "__main__":
      k = Result()
      k.append_dataset(x=[2, 4])
      k.debug()

How to inherit Pandas class More information in here Inheriting Pandas

import pandas as pd

class Result(pd.DataFrame):

  @property
  def _constructor(self):
      return Result


if __name__ == "__main__":
    k = Result(data=[2, 4], columns=['a'])
    tem_data = pd.DataFrame(data=[5, 6], columns=['a'])
    k = k.append(tem_data)
    print(k)
Aybars
  • 395
  • 2
  • 11
  • Thanks @Aybars. Is there a way to keep the inheritance strucutre? i.e. so that Result inherits from pd.DataFrame? – Tim Mak Dec 07 '18 at 09:23
  • @TimMak, yes, you can. I have updated my answer. I hope it will help. You can find more information about it at http://pandas.pydata.org/pandas-docs/stable/extending.html#extending-subclassing-pandas – Aybars Dec 07 '18 at 09:49
  • @TimMak, if the post answers your question, please accept it as a solution. – Aybars Dec 07 '18 at 10:13
  • I think I have. – Tim Mak Dec 08 '18 at 11:36