【问题标题】:Reading the csv and formatting it to a dictionary with Pandas Python使用 Pandas Python 读取 csv 并将其格式化为字典
【发布时间】:2021-08-07 08:01:25
【问题描述】:

我正在尝试将下面的代码转换为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

【问题讨论】:

    标签: python-3.x pandas dictionary for-loop format


    【解决方案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]
    

    【讨论】:

      猜你喜欢
      • 2021-08-06
      • 2022-01-27
      • 1970-01-01
      • 2018-03-19
      • 2016-12-06
      • 2022-07-04
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多