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.
CodePudding user response:
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=';', header=0, index_col=['project'], usecols=["project", "item", "maker",])
for index, item in df.iterrows():
Item(
project=item['project'],
price=str(item['item')]),
quantity=str(item['maker']),
)