Pythonic方法根据日期示例过滤DataFrame

时间:2015-05-08 19:31:51

标签: python pandas

In [90]: list_dates = [datetime.date(2014,2,2),datetime.date(2015,2,2), datetime.date(2013,4,5)]

In [91]: df = DataFrame(list_dates, columns=['Date'])

In [92]: df
Out[92]: 
         Date
0  2014-02-02
1  2015-02-02
2  2013-04-05

现在我想获得一个新的DataFrame,其中只包含2014年和2013年的日期:

In [93]: result = DataFrame([date for date in df.Date if date.year in (2014,2013)])

In [94]: result
Out[94]: 
            0
0  2014-02-02
1  2013-04-05

这有效,并为我提供了所需的DataFrame。 为什么没有以下工作:

In [95]: result1 = df[df.Date.map(lambda x: x.year) == 2014 or p.Date.map(lambda x: x.year) == 2013]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-95-86f01906c89b> in <module>()
----> 1 result1 = df[df.Date.map(lambda x: x.year) == 2014 or p.Date.map(lambda x: x.year) == 2013]

/home/marcos/anaconda/lib/python2.7/site-packages/pandas/core/generic.pyc in __nonzero__(self)
    690         raise ValueError("The truth value of a {0} is ambiguous. "
    691                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 692                          .format(self.__class__.__name__))
    693 
    694     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

或以下内容:

In [96]: df['year'] = df.Date.map(lambda x: x.year)

In [97]:     result2 = df[df.year in (2014, 2013)]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-97-814358a4edff> in <module>()
----> 1 result2 = df[df.year in (2014, 2013)]

/home/marcos/anaconda/lib/python2.7/site-packages/pandas/core/generic.pyc in __nonzero__(self)
    690         raise ValueError("The truth value of a {0} is ambiguous. "
    691                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 692                          .format(self.__class__.__name__))
    693 
    694     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我认为问题在于,当我使用&#39;&#39;命令我试图检查整个系列是否在元组中。但是,如何使评估成为元素,以便获得我想要的结果?

1 个答案:

答案 0 :(得分:3)

我会使用to_datetime将日期转换为日期时间对象,然后您可以使用dt访问者访问year属性,然后我们可以调用{{3}并传递一个感兴趣的年份列表来过滤df:

In [68]:

df['Date'] = pd.to_datetime(df['Date'])
In [69]:

df[df['Date'].dt.year.isin([2013,2014])]
Out[69]:
        Date
0 2014-02-02
2 2013-04-05