2015-11-12 59 views
0

我的pandas.DataFrame包含一個包含時間戳值的列。基於列值的屬性值篩選DataFrame的行

我特別想使用那些位於特定時間範圍內的行,從開始小時到結束小時,忽略日期部分。

我試圖實現這個使用布爾數組作爲索引:

import datetime 
import pandas 
from random import randrange as rr 

# generate random timestamps 
timestamps = [datetime.datetime(2000,1,1,rr(24),rr(60)) for i in xrange(100)] 
# insert into DataFrame 
df = pandas.DataFrame(timestamps, columns=["t"]) 
# try to filter based on time range 
morning = df[8 <= df.t.hour < 12] 

不幸的是,這並不工作:

Traceback (most recent call last): 
    File "test.py", line 9, in <module> 
    morning = df[8 <= df.t.hour < 12] 
    File "/usr/lib/python2.7/dist-packages/pandas/core/generic.py", line 1815, in __getattr__ 
    (type(self).__name__, name)) 
AttributeError: 'Series' object has no attribute 'hour' 

我試圖解決此問題:

morning = df[8 <= df.t.apply(lambda x:x.hour) < 12] 

但是這也失敗了:

Traceback (most recent call last): 
    File "test.py", line 16, in <module> 
    morning = df[8 <= df.t.apply(lambda x:x.hour) < 12] 
    File "/usr/lib/python2.7/dist-packages/pandas/core/generic.py", line 676, in __nonzero__ 
    .format(self.__class__.__name__)) 
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

任何人都可以提出一種方法,如何根據列值的屬性的值篩選DataFrame的行?

回答

2

你想以下幾點:

df[(df['t'].dt.hour >= 8) & (df['t'].dt.hour < 12)] 

首先爲D型是datetime64那麼你就有dt存取僅返回hour組件,您可以使用它進行比較。

當你正在尋找一個範圍,那麼你需要使用&運營商,因爲我們正在處理的陣列使用2個條件and,敷在括號中的條件下,由於運算符優先級

In [236]: 
morning = df[(df['t'].dt.hour >= 8) & (df['t'].dt.hour < 12)] 
morning 

Out[236]: 
        t 
8 2000-01-01 09:09:00 
18 2000-01-01 10:30:00 
20 2000-01-01 11:58:00 
21 2000-01-01 10:11:00 
22 2000-01-01 10:39:00 
32 2000-01-01 08:51:00 
35 2000-01-01 10:32:00 
42 2000-01-01 10:57:00 
46 2000-01-01 11:45:00 
55 2000-01-01 08:58:00 
56 2000-01-01 10:26:00 
60 2000-01-01 10:33:00 
66 2000-01-01 11:13:00 
70 2000-01-01 10:29:00 
79 2000-01-01 08:23:00 
80 2000-01-01 08:08:00 
83 2000-01-01 10:44:00 
86 2000-01-01 11:02:00 
93 2000-01-01 11:14:00 
97 2000-01-01 08:55:00 
98 2000-01-01 10:47:00 
+0

所以現在抱怨「Series」對象沒有屬性「dt」。我使用的是'0.13.1'版本 - 這個功能在更高版本中可用嗎? – moooeeeep

+1

是的,您需要升級至少['0.15.0'](http://pandas.pydata.org/pandas-docs/version/0.17.0/whatsnew.html#dt-accessor) – EdChum