Instantiate from csv with pandas

Question:

I have previously made a code to instantiate from a csv file. I what to do the same with Pandas (gives more possibilities when importing csv file). Is this possible?

What I want (without Pandas):

    @classmethod
    def instantiate_from_csv(cls):
        with open('items.csv', 'r') as f:
            reader = csv.DictReader(f)
            items = list(reader)

        for item in items:
            Item(
                project=item.get('project'),
                price=str(item.get('item')),
                quantity=str(item.get('maker')),
            )

What I have:


import pandas as pd

df = pd.read_csv('items.csv', sep=';', header=0, index_col=['project'], usecols=["project", "item", "maker",])

print(df)

Any help is greatly appreciated.

Asked By: Shesch

||

Answers:

Not sure if I understood your question correctly. If what you’re looking for is "what you want" (first piece of code) but reading with Pandas, then this is what you might be looking for:

import pandas as pd

def instantiate_from_csv(cls):
    df = pd.read_csv('items.csv', sep=';', usecols=["project", "price", "quantity",])

    for index, item in df.iterrows():
        Item(
            project=item['project'],
            price=str(item['item']),
            quantity=str(item['maker']),
        )
Answered By: Jau A
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.