Home > Net >  Create a DataFrame with data from a class
Create a DataFrame with data from a class

Time:12-03

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!

CodePudding user response:

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'])

CodePudding user response:

You can create a DataFrame from a list of Transaction objects by first creating a list of dictionaries, where each dictionary represents a row in the DataFrame and has keys that correspond to the columns. Here's one way to do it:

import pandas as pd

# Create a list of Transaction objects
transactions = [t1, t2, t3]

# Create a list of dictionaries, where each dictionary represents a row in the DataFrame
data = []
for t in transactions:
    row = {"Date": t.date, "Concept": t.concept, "Amount": t.amount}
    data.append(row)

# Create a DataFrame from the list of dictionaries, specifying the columns in the desired order
df = pd.DataFrame(data, columns=["Date", "Concept", "Amount"])

# Print the DataFrame
print(df)

This should produce a DataFrame that looks like this:

|    | Date     | Concept   | Amount   |
|---:|:---------|:----------|:---------|
|  0 | 20221128 | C1        |       14 |
|  1 | 20221129 | C2        |       30 |
|  2 | 20221130 | 3         |       14 |

The above code assumes that the Transaction class is defined as you have shown in your question, with the __init__ method and the class variables and methods that you have included. Note that I have replaced Transaction with Transactions in the class definition to match the name of the class, and I have also changed the self parameter of the add_money method to transaction, to avoid confusion with the self parameter of the instance methods. The DataFrame function is not part of the class definition, but is defined as a separate function that takes a list of Transaction objects as its argument.

You can also add a class method to the Transactions class that returns a DataFrame representing all the instances of the class. To do this, you can add a class variable transactions_list that keeps track of all the instances of the class, and a class method to_dataframe that converts transactions_list to a DataFrame.

Here's one way to implement it:

import pandas as pd

class Transactions:

    num_of_transactions = 0
    amount = 0
    transactions_list = []  # Class variable to store all instances of the class

    def __init__(self, date, concept, amount):
        self.date = date
        self.concept = concept
        self.amount = amount
        # Add the instance to the transactions_list
        self.transactions_list.append(self)
        Transactions.add_transaction()
        Transactions.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

    @classmethod
    def to_dataframe(cls):
        # Create a list of dictionaries representing each transaction
        transactions_list = [{'Date': t.date, 'Concept': t.concept, 'Amount': t.amount} for t in cls.transactions_list]

        # Create a DataFrame from the list of dictionaries
        df = pd.DataFrame(transactions_list)

        return df

# Create some transactions
t1 = Transactions("20221128", "C1", 14)
t2 = Transactions("20221129", "C2", 30)
t3 = Transactions("20221130", "3", 14)

You can then call the class method to_dataframe to get a DataFrame representing all the transactions:

df = Transactions.to_dataframe()

This should create a DataFrame df with columns 'Date', 'Concept', and 'Amount' and rows corresponding to each transaction.

  • Related