python- pandas -检查数据框中是否存在日期 [英] python - pandas - check if date exists in dataframe
问题描述
我有一个像这样的数据框:
I have a dataframe like this:
category date number
0 Cat1 2010-03-01 1
1 Cat2 2010-09-01 1
2 Cat3 2010-10-01 1
3 Cat4 2010-12-01 1
4 Cat5 2012-04-01 1
5 Cat2 2013-02-01 1
6 Cat3 2013-07-01 1
7 Cat4 2013-11-01 2
8 Cat5 2014-11-01 5
9 Cat2 2015-01-01 1
10 Cat3 2015-03-01 1
我想检查此数据框中是否存在日期,但无法执行.我尝试了以下各种方法,但仍然没有用:
I would like to check if a date is exist in this dataframe but I am unable to. I tried various ways as below but still no use:
if pandas.Timestamp("2010-03-01 00:00:00", tz=None) in df['date'].values:
print 'date exist'
if datetime.strptime('2010-03-01', '%Y-%m-%d') in df['date'].values:
print 'date exist'
if '2010-03-01' in df['date'].values:
print 'date exist'
日期存在"从未打印过.如何检查日期是否存在?因为我想在所有类别中插入数字不等于0的不存在日期,以便绘制连续的折线图(每条线一个类别).感谢您的帮助.提前致谢.
The 'date exist' never got printed. How could I check if the date exist? Because I want to insert the none-existed date with number equals 0 to all the categories so that I could plot a continuously line chart (one category per line). Help is appreciated. Thanks in advance.
最后一个给我这个:
FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
并且date exist
无法打印.
The last one gives me this:
FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
And the date exist
not get printed.
推荐答案
我认为您首先需要通过 boolean indexing
:
I think you need convert to datetime first by to_datetime
and then if need select all rows use boolean indexing
:
df.date = pd.to_datetime(df.date)
print (df.date == pd.Timestamp("2010-03-01 00:00:00"))
0 True
1 False
2 False
3 False
4 False
5 False
6 False
7 False
8 False
9 False
10 False
Name: date, dtype: bool
print (df[df.date == pd.Timestamp("2010-03-01 00:00:00")])
category date number
0 Cat1 2010-03-01 1
要返回True
,请使用由numpy array的检查值"nofollow noreferrer"> values
:
For return True
use check value converted to numpy array
by values
:
if ('2010-03-01' in df['date'].values):
print ('date exist')
if (df.date == pd.Timestamp("2010-03-01 00:00:00")).any():
print ('date exist')
这篇关于python- pandas -检查数据框中是否存在日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!