Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a class with a pandas DataFrame and filling it

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!

like image 438
Tim Mak Avatar asked Sep 07 '25 14:09

Tim Mak


1 Answers

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)
like image 129
Aybars Avatar answered Sep 09 '25 06:09

Aybars