Reading the csv and formatting it to a dictionary with Pandas Python

Viewed 36

I ma trying to convert the Code below to pandas. How would I be able to do convert to have both reader functions equivalent so that account_strats function works. The pandas implementation is faulty giving error defined below, how would I be able to fix it and convert it into pandas type.

CSV:

Name,AccountName,Type
XXX,Account1,RSIStrategy
XYB,Account1,MACDStrategy2.0
XBR,Account1,STDandRegressionStrategy

Code that works:

import csv 

for account in range(2):
    file = open("SavedStrats.csv")
    reader = csv.DictReader(file)
    account_strats = [strat for strat in reader if strat["AccountName"] == account]
    file.close()

Pandas Implementation(Code faulty):

import pandas as pd

for account in range(2):
    reader= pd.read_csv("SavedStrats.csv").to_dict('dict')
    account_strats = [strat for strat in reader if strat["AccountName"] == account]

Error:

TypeError: string indices must be integers
1 Answers

For your requirement, what you need is to_dict('records')

import pandas as pd

for account in range(2):
    reader= pd.read_csv("SavedStrats.csv").to_dict('records')
    account_strats = [strat for strat in reader if strat["AccountName"] == account]
Related