Python 在数据框中搜索日期
我试图搜索熊猫数据框中是否存在特定的日期,但是,我看到一些特定的奇怪行为,如下所示。我是python和pandas的新手,因此非常感谢您的帮助 示例数据帧:Python 在数据框中搜索日期,python,pandas,time-series,Python,Pandas,Time Series,我试图搜索熊猫数据框中是否存在特定的日期,但是,我看到一些特定的奇怪行为,如下所示。我是python和pandas的新手,因此非常感谢您的帮助 示例数据帧: >>> hd.dtypes Date datetime64[ns] NAV float64 dtype: object >>> hd.head() Date NAV 2004-04-01 41.106
>>> 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
基本上,我试图找到一个特定的日期“下一天”出现在hd['date']
中,如下所示。代码总是返回not present
,这让我感到困惑。我曾尝试将下一天
设置为hd
数据框中的第一个日期,该日期应始终满足-但仍显示不存在
。
但是,当我使用非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
它与日期时间转换有关吗?您不能使用该方法进行测试,您可以使用
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不在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