【问题标题】:Can't figure out why I keep getting a KeyError while trying to the number of a CSV row无法弄清楚为什么我在尝试获取 CSV 行数时不断收到 KeyError
【发布时间】:2021-03-03 10:56:45
【问题描述】:

代码非常简单,单元格的内容与我写入代码的内容完全相同。只是试图获取代码列 = A 的所有时间的行号。

代码:

import pandas as pd

filename = 'DataFiles/SHARADAR_SF1_aafe962511a67db10c0a72fe536305b0.csv'
pattern = 'AAPL'

df = pd.read_csv(filename, index_col=0)

rows = df[df['ticker'] == pattern].index.to_list()

CSV 示例(文件后面有更多代码,例如 AAPL 或 TSLA 等):

ticker,dimension,calendardate,datekey,lastupdated,assets,assetsavg,cashneq,debt,debtc,debtusd,divyield,deposits,eps,epsusd,equity,equityavg,liabilities,netinc,pe,price,revenue
A,ARQ,1999-12-31,2000-03-15,2020-09-01,7107000000,,1368000000,665000000,111000000,665000000,0,0,0.3,0.3,4486000000,,2621000000,131000000,,114.3,2246000000
A,ARQ,2000-03-31,2000-06-12,2020-09-01,7321000000,,978000000,98000000,98000000,98000000,0,0,0.37,0.37,4642000000,,2679000000,166000000,,66,2485000000
A,ARQ,2000-06-30,2000-09-01,2020-09-01,7827000000,,703000000,129000000,129000000,129000000,0,0,0.34,0.34,4902000000,,2925000000,155000000,46.877,61.88,2670000000
A,ARQ,2000-09-30,2001-01-17,2020-09-01,8425000000,,996000000,110000000,110000000,110000000,0,0,0.67,0.67,5265000000,,3160000000,305000000,37.341,61.94,3372000000
A,ARQ,2000-12-31,2001-03-19,2020-09-01,9208000000,,433000000,556000000,556000000,556000000,0,0,0.34,0.34,5541000000,,3667000000,154000000,21.661,36.99,2841000000

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这里,使用index_col 作为None,否则ticker 是索引列:

    import pandas as pd
    
    filename = 'DataFiles/SHARADAR_SF1_aafe962511a67db10c0a72fe536305b0.csv'
    pattern = 'AAPL'
    
    df = pd.read_csv(filename, index_col=None)
    
    rows = df[df['ticker'] == pattern].index.to_list()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2018-12-03
      • 2017-06-15
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      相关资源
      最近更新 更多