3

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

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

When doing a loop trough the rows of 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

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?

user3276418
  • 1,777
  • 4
  • 20
  • 29

1 Answers1

1

The documentation provides a number of ways to index a datetime index DataFrame, a few examples:

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
CT Zhu
  • 52,648
  • 17
  • 120
  • 133