0

I want to create a DataFrame to which I want to import data from a class. I mean, I type t1 = Transaction("20221128", "C1", 14) and I want a DataFrame to show data like:

  1. Column 1: Date
  2. Column 2: Concept
  3. Column 3: Amount

The code where I want to implement this is:

class Transactions:

    num_of_transactions = 0
    amount = 0

    def __init__(self, date, concept, amount):
        self.date = date
        self.concept = concept
        self.amount = amount
        Transaction.add_transaction()
        Transaction.add_money(self)

    @classmethod
    def number_of_transactions(cls):
        return cls.num_of_transactions

    @classmethod
    def add_transaction(cls):
        cls.num_of_transactions += 1

    @classmethod
    def amount_of_money(cls):
        return cls.amount

    @classmethod
    def add_money(cls, self):
        cls.amount += self.amount

t1 = Transaction("20221128", "C1", 14)
t2 = Transaction("20221129", "C2", 30)
t3 = Transaction("20221130", "3", 14)

I tried:

def DataFrame(self):
    df = pd.DataFrame(self.date self.concept, self.amount)

But looking at pandas documentation, I have seen it is not a valid way.

Any help on that? Thank you!

2 Answers 2

1

In order to create a new data frame, you have to provide the rows and the columns name.

You have to change the code as the following:

def DataFrame(self):
    df = pd.DataFrame(data=[[self.date, self.concept, self.amount]], columns=['Date','Concept','Amount'])
Sign up to request clarification or add additional context in comments.

Comments

1

for the example you provided we can do some modifications in the class so we could get a dataframe easily:

class Transaction:

    num_of_transactions = 0
    amount = 0
    transactions = []  # <----- class atribute added

    def __init__(self, date, concept, amount):
        self.date = date
        self.concept = concept
        self.amount = amount
        Transaction.add_transaction()
        Transaction.add_money(self)
        Transaction.transactions.append(self)  # <----- append added

now we can get a dataframe like this:

pd.DataFrame([t.__dict__ for t in Transaction.transactions])

>>>
'''
       date concept  amount
0  20221128      C1      14
1  20221129      C2      30
2  20221130       3      14

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.