pandas 日期时间索引 KeyError: '标签 [2000-01-03 00:00:00] 不在 [索引]'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26863481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:39:06  来源:igfitidea点击:

datetime index KeyError: 'the label [2000-01-03 00:00:00] is not in the [index]'

pythondatetimepandas

提问by user3276418

I have a pandas dataframe generated by

我有一个由

dates = pandas.date_range('1/1/2000', periods=8)
df = pandas.DataFrame(rd.randn(8, 5), index=dates, columns=['call/put', 'expiration', 'strike', 'ask', 'bid'])
df.iloc[2,4]=0
df.iloc[2,3]=0
df.iloc[3,4]=0
df.iloc[3,3]=0
df.iloc[2,2]=0.5
df=df.append(df.iloc[2:3])
df.iloc[8:9,3:5]=1
df.iloc[8:9,2:3]=0.6
df=df.append(df.iloc[8:9])
df.iloc[9,2]=0.4

from df I obtain df4 by

从 df 我获得 df4

df4=df[(df["ask"]==0) & (df["bid"]==0)]

When doing a loop trough the rows of df4

当通过 df4 的行进行循环时

for index, row in df4.iterrows():
  print index
  df_upperbound = df.iloc[index]

I get index KeyError: 'the label [2000-01-03 00:00:00] is not in the [index]'. When trying

我得到索引 KeyError: '标签 [2000-01-03 00:00:00] 不在 [索引] 中。尝试时

for index, row in df4.iterrows():
  print index
  df_upperbound = df.xs[index]

I get TypeError: 'instancemethod' object has no attribute 'getitem'. I use pandas 0.14.0 and python 2.7.7. How can I iterate through the index entrys of df4 within df?

我得到 TypeError: 'instancemethod' object has no attribute ' getitem'。我使用Pandas 0.14.0 和 python 2.7.7。如何在 df 中遍历 df4 的索引条目?

采纳答案by CT Zhu

The documentationprovides a number of ways to index a datetimeindex DataFrame, a few examples:

文档提供了多种索引datetime索引的方法DataFrame,一些示例:

In [64]:

index
Out[64]:
Timestamp('2000-01-03 00:00:00')
In [65]:

print df.ix[index.to_datetime()]
            call/put  expiration  strike  ask  bid
2000-01-03  0.830035    -0.42598     0.5    0    0
2000-01-03  0.830035    -0.42598     0.6    1    1
2000-01-03  0.830035    -0.42598     0.4    1    1
In [66]:

print df.ix[index]
            call/put  expiration  strike  ask  bid
2000-01-03  0.830035    -0.42598     0.5    0    0
2000-01-03  0.830035    -0.42598     0.6    1    1
2000-01-03  0.830035    -0.42598     0.4    1    1
In [67]:

print df[index.strftime('%m/%d/%y')]
            call/put  expiration  strike  ask  bid
2000-01-03  0.830035    -0.42598     0.5    0    0
2000-01-03  0.830035    -0.42598     0.6    1    1
2000-01-03  0.830035    -0.42598     0.4    1    1