提取datafram中第一项时的关键错误

2024-06-09 00:39:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这段代码建立了一个来自data的datafames字典,它本身就是一个数据帧。data从文件中读取:

data = pandas.read_csv(QuoteData, usecols=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22])

因为data数据帧混合了许多不同的时间帧,所以我将它们分离到按时间索引的数据帧字典中。然后,字典中的每个数据帧都按照所示的条件进行排序。你知道吗

无论我尝试什么,我都无法访问dodf[k]['underlying_bid']的first元素。因此,例如dodf[k]['underlying_bid'][0]对第一个数据帧有效,但在循环的第二次崩溃。0是第一个数据帧列的键,而不是第二个数据帧列的键?你知道吗

Traceback (most recent call last):
  File "cboelivedata.py", line 481, in <module>
    main()
  File "cboelivedata.py", line 422, in main
    underlyingprice = dodf[k]['underlying_bid'][0]
  File "/home/idf/anaconda2/lib/python2.7/site-packages/pandas/core/series.py", line 583, in __getitem__
    result = self.index.get_value(self, key)
  File "/home/idf/anaconda2/lib/python2.7/site-packages/pandas/indexes/base.py", line 1980, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas/index.pyx", line 103, in pandas.index.IndexEngine.get_value (pandas/index.c:3332)
  File "pandas/index.pyx", line 111, in pandas.index.IndexEngine.get_value (pandas/index.c:3035)
  File "pandas/index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)
  File "pandas/hashtable.pyx", line 303, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6610)
  File "pandas/hashtable.pyx", line 309, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6554)
KeyError: 0

代码片段:

dodf = {name: group for name, group in data.groupby('quote_datetime')}
dodf = collections.OrderedDict(sorted(dodf.items(), key=lambda x: x[0]))#key=operator.itemgetter))

for k in dodf:   
        df = dodf[k].sort_values(['option_type', 'Strike', 'Expiration'], ascending=True)  
        underlyingprice = dodf[k]['underlying_bid'] # **What goes here?**

Tags: 数据inpypandasdatagetindexvalue