我正在尝试将下面的代码转换为 pandas
。我如何才能转换为具有等效的 reader
函数,以便 account_strats
函数起作用。 pandas
实现有错误,给出下面定义的错误,我该如何修复它并将其转换为 pandas
类型。
CSV:
Name,AccountName,Type
XXX,Account1,RSIStrategy
XYB,Account1,MACDStrategy2.0
XBR,Account1,STDandRegressionStrategy
有效的代码:
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 实现(代码错误):
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]
错误:
TypeError: string indices must be integers
答案 0 :(得分:1)
对于您的要求,您需要的是 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]