2015-04-05 72 views
0

我想搜索一个特定的日期是否存在于一个熊猫数据框中,但是,我发现了一些特殊的日期行为,如下所示。我对Python和熊猫是新手 - 所以任何帮助表示赞赏。在熊猫数据框内搜索日期

样品数据框:

>>> hd.dtypes 
    Date datetime64[ns] 
    NAV   float64 
    dtype: object 

>>> hd.head() 
    Date   NAV 
    2004-04-01  41.106 
    2004-04-02  41.439 
    2004-04-05  41.727 
    2004-04-06  41.667 
    2004-04-07  41.770 

基本上我试图找到一个特定日期“NEXT_DAY”存在于hd['Date']作为below.The代码总是返回not present这令我感到困惑。我试图将next_day设置为hd数据帧中的第一个日期,该数据帧应始终满足 - 但它仍显示not present。 然而代码工作当我使用非datetime列:

>>> next_day = hd['Date'][0] 
>>> if (next_day not in hd['Date']): 
     print 'not present' 
    else: 
     print 'present' 
>>> not present 
>>>if (41.106 not in hd['NAV']): 
    print 'not present' 
    else: 
    print 'present' 
>>> present 

这是否与日期时间转换?

回答

0

您不能使用这种方法来测试你可以使用isin

hd['Date'].isin([next_day])In [5]: 

df['Date'].isin([next_day]) 
Out[5]: 
0  True 
1 False 
2 False 
3 False 
4 False 
Name: Date, dtype: bool 

这里的问题是,你试图用一个数组来比较单一的值,所以你会得到意想不到的结果:

In [8]: 

next_day in df['Date'] 
Out[8]: 
False 
In [7]: 

next_day not in df['Date'] 
Out[7]: 
True 

我也无法重现你的另一说法:

In [17]: 

41.106 in df['NAV'] 
Out[17]: 
False 

因此,正确的方法是使用isin并传递一系列或列表以检查传入列表中的值是否存在于您的系列中,如上所示,无论您看到的结果是否为虚假,并且与41.106 not in hd['NAV']不正确。

您可以使用与==操作沿any检查成员:

In [18]: 

next_day == df['Date'] 
Out[18]: 
0  True 
1 False 
2 False 
3 False 
4 False 
Name: Date, dtype: bool 
In [19]: 

(next_day == df['Date']).any() 
Out[19]: 
True