Skip to main content
 首页 » 编程设计

python之提取数据框中第一项的关键错误

2025年02月15日10wuhuacong

这段代码从 data 中建立了一个数据名字典,它本身就是一个数据框。 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'] 的第一个元素。因此,例如 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?** 

请您参考如下方法:

比我想象的要容易得多

dodf[k]['underlying_bid'].iloc[0]