python- pandas -检查数据框中是否存在日期 [英] python - pandas - check if date exists in dataframe

查看:103
本文介绍了python- pandas -检查数据框中是否存在日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

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.

推荐答案

我认为您首先需要通过

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')

或由 any 作为评论 Edchum :

if (df.date == pd.Timestamp("2010-03-01 00:00:00")).any():
    print ('date exist')  

这篇关于python- pandas -检查数据框中是否存在日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆