过滤pandas数据帧

时间:2014-11-10 18:06:53

标签: python-2.7 pandas dataframe

我有一个pandas数据帧df,包括列到期日期,警示,看涨/看跌,买入和卖出。索引是datetime。我想过滤ask = 0和bid = 0的行,这些行包含在dataframe df4中。我想检查该数据帧中是否还有其他行,其中包含相同的到期日期和调用/放置值,相同的日期时间索引条目,出价和要求不等于零以及具有上限和下限的定义步骤的警示bid = ask = 0的列的列表。如果是,则应该进行一些操作(在投标和询问罢工之间进行插值)。

我提出了以下代码,但它引发了KeyError:'标签[xy]不在[index]'中,显然是由于某些日期时间格式化问题。该脚本遍历数据帧行。

这是我的问题: a)如何编码才能正常工作? b)有没有办法完全向量化这个,因为我的真实世界数据样本相当大,大约2 GB?

以下是代码,我希望它至少可以解释我正在尝试做的事情:

# constructing a sample dataframe
import pandas
import numpy.random as rd
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

#filtering for rows with bid=ask=0
df4=df[(df["ask"]==0) & (df["bid"]==0)]

#checking for rows that can be used for bid and ask interpolation
stepsize=0.1
counter=0
for index, row in df4.iterrows():
 print index
 df_upperbound = df.loc[index]
 df_upperbound = df_upperbound[(df_upperbound['call/put']== df4['call/put']) &  (df_upperbound['expiration']== df4['expiration']) & (df_upperbound['strike']== df4['strike']+stepsize)]
 df_lowerbound = df.loc[index]
 df_lowerbound = df_lowerbound[ (df_lowerbound['call/put']== df4['call/put']) & (df_lowerbound['expiration']== df4['expiration']) & (df_lowerbound['strike']== df4['strike']-stepsize)]
 if len(df_upperbound)>0 and len(df_lowerbound)>0:
    is_upperbound = df_upperbound.ask!=0 and df_upperbound.bid!=0
    is_lowerbound = df_lowerbound.ask!=0 and df_lowerbound.bid!=0  
    if is_upperbound and is_lowerbound:
        counter+=1

1 个答案:

答案 0 :(得分:1)

这只是一种解决方法,但使用strftime(from here)似乎有效......

In[8] stepsize=0.1
      counter=0
      for index,row in df4.iterrows():
          print df[index.strftime('%Y-%m-%d')]


Out[9] call/put  expiration  strike  ask  bid
       2000-01-03  0.181998   -2.371192     0.5    0    0
       2000-01-03  0.181998   -2.371192     0.6    1    1
       2000-01-03  0.181998   -2.371192     0.4    1    1
           call/put  expiration    strike  ask  bid
       2000-01-04  0.030905    1.142885 -1.268263    0    0
相关问题