簡體   English   中英

根據列值的屬性值過濾DataFrame的行

[英]Filter rows of a DataFrame based on the value of an attribute of a column value

我的pandas.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的行?

您需要以下內容:

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

首先,由於dtype是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM