我正在处理一个包含多年数据且每个值带有时间戳的dataFrame。我正在努力对夏季/非夏季月份的数据进行排序。我不确定如何告诉大熊猫获取日期为6月15日至9月15日的数据,但是会丢弃年份。
df['is_summer'] = df['Date'].dt.month.between(6,9) # This works for June 1 to September 30 for every year
# I want to do this, this is pseudo code
df['is_summer'] = df['Date'].dt.day.between(6-15,9-15) # From June 15 to September 15 for every year
# I also want to this
df['is_late_night'] = df['Date'].dt.time.between(20:00,23:59) # From 20:00 to 23:59 for every day
我很难找到有关此问题的文档。我想知道时间,月份,日期和年份的.between()的正确语法。 谢谢您的帮助
答案 0 :(得分:1)
我将其分为3个更简单的条件
df = pd.DataFrame({'date': pd.date_range(start='1/1/2016', end='1/08/2018')})
select_month78 = df.date.dt.month.between(7,8)
select_month6 = (df.date.dt.month==6) & (df.date.dt.day >= 15)
select_month9 = (df.date.dt.month==9) & (df.date.dt.day <= 15)
df['is_summer'] = select_month78 | select_month6 | select_month9
df[df.is_summer]
输出:
date is_summer
166 2016-06-15 True
167 2016-06-16 True
168 2016-06-17 True
169 2016-06-18 True
170 2016-06-19 True
.. ... ...
619 2017-09-11 True
620 2017-09-12 True
621 2017-09-13 True
622 2017-09-14 True
623 2017-09-15 True
[186 rows x 2 columns]
答案 1 :(得分:1)
您可以使用布尔掩码过滤熊猫数据框,它看起来像这样:
import numpy as np
import pandas as pd
# creating random date ranging across many years
df = pd.DataFrame(np.random.random((1000,3)))
df['date'] = pd.date_range('2000-1-1', periods=1000, freq='D')
# Creating the boolean mask to keep everything from June to August
mask = (df['date'].dt.month > 6) & (df['date'].dt.month <= 8)
# Applying the boolean mask to the data frame an printing it
print(df.loc[mask])
可以在过滤步骤中嵌入遮罩创建,因此在您的情况下,解决方案是一个衬套
only_summer_data = df.loc[(df['date'].dt.month >= 6) & (df['date'].dt.month <= 8))
如果您也想有一天,我们将获得以下信息:
start_mask = ((df['date'].dt.month == 6) & (df['date'].dt.day >= 15)) | (df['date'].dt.month > 6)
end_mask = ((df['date'].dt.month == 8) & (df['date'].dt.day <= 15)) | (df['date'].dt.month < 8)
mask = start_mask & end_mask
print(df.loc[mask])
但是,随着对日期过滤的控制更加细化,布尔掩码解决方案可能会变得非常冗长。
答案 2 :(得分:1)
使用dayofyear
组件定义范围并进行比较-这将使您可以将过滤器限制为不考虑年份的日期范围。
>>> start = pd.to_datetime('06-15-2000').dayofyear
>>> end = pd.to_datetime('09-15-2000').dayofyear
>>> start,end
(167, 259)
>>> df = pd.DataFrame(pd.date_range('2010-01-01', periods=52, freq='SM'),columns=['Date'])
>>> df[(df['Date'].dt.dayofyear >= start) & (df['Date'].dt.dayofyear <= end)]
Date
11 2010-06-30
12 2010-07-15
13 2010-07-31
14 2010-08-15
15 2010-08-31
16 2010-09-15
35 2011-06-30
36 2011-07-15
37 2011-07-31
38 2011-08-15
39 2011-08-31
40 2011-09-15
>>>
或
>>> df.loc[df['Date'].dt.dayofyear.between(start,end)]