Python 是否按列中日期的特定月份对数据帧进行子集?

Python 是否按列中日期的特定月份对数据帧进行子集?,python,pandas,Python,Pandas,如何对数据帧进行子集,以获取包含特定月份数据的行 我有一个2010-01-01格式的日期列 如果它被索引,我会使用 df.ix[date1:date2] 但是,如果数据在列中,我该怎么办?可以使用掩码来选择数据帧中的范围 遮罩只是普通的pd。序列包含True和False元素 使用仆从的一般示例: df_minions = pd.DataFrame({ 'color':['Red', 'Green', 'Blue', 'Brown'] * 2, 'name':['Burnie',

如何对数据帧进行子集,以获取包含特定月份数据的行

我有一个2010-01-01格式的日期列

如果它被索引,我会使用

df.ix[date1:date2]

但是,如果数据在列中,我该怎么办?

可以使用掩码来选择数据帧中的范围

遮罩只是普通的
pd。序列
包含
True
False
元素

使用仆从的一般示例:

df_minions = pd.DataFrame({
    'color':['Red', 'Green', 'Blue', 'Brown'] * 2,
    'name':['Burnie', 'Stinky', 'Swimmy', 'Bashy', 'Flamie', 'Stabbie', 'Blubb', 'Smashie']})
   color     name
0    Red   Burnie
1  Green   Stinky
2   Blue   Swimmy
3  Brown    Bashy
4    Red   Flamie
5  Green  Stabbie
6   Blue    Blubb
7  Brown  Smashie
选择所有棕色爪牙可以很容易地做到如下:

brown_minion_mask = df_minions['color'] == 'Brown'
0    False
1    False
2    False
3     True
4    False
5    False
6    False
7     True

df_minions[brown_minion_mask]
   color     name
3  Brown    Bashy
7  Brown  Smashie
现在,关于选择日期的月份的具体问题:

首先,我将添加一个
sprowned
列,其中满是日期

df_minions['spawned'] = [datetime(2015, m, 5) for m in range(4,6)] * 4
   color     name    spawned
0    Red   Burnie 2015-04-05
1  Green   Stinky 2015-05-05
2   Blue   Swimmy 2015-04-05
3  Brown    Bashy 2015-05-05
4    Red   Flamie 2015-04-05
5  Green  Stabbie 2015-05-05
6   Blue    Blubb 2015-04-05
7  Brown  Smashie 2015-05-05
现在我们可以访问非常特殊的
pd.TimeSeries
,它是

我们可以使用这个操作来屏蔽我们的数据帧,就像我们对我们的爪牙的颜色所做的一样

may_minion_mask = df_minions.spawned.dt.month == 5
df_minions[may_minion_mask]
   color     name    spawned
1  Green   Stinky 2015-05-05
3  Brown    Bashy 2015-05-05
5  Green  Stabbie 2015-05-05
7  Brown  Smashie 2015-05-05
当然,你可以在面具上做任何你想做的操作

not_spawned_in_january = df_minions.spawned.dt.month != 1
summer_minions = ((df_minions.spawned > datetime(2015,5,15)) &
                  (df_minions.spawned < datetime(2015,9,15))
name_endswith_y = df_minions.name.str.endswith('y')
not_sprowned_in_一月=df_minions.sprowned.dt.month!=1.
夏季爪牙=((df_minions.sprowned>datetime(2015,5,15))&
(df_minions.spoked<日期时间(2015,9,15))
name_endswith_y=df_minions.name.str.endswith('y'))
你的意思是像
df[(df['date']>=date1)和(df['date']
not_spawned_in_january = df_minions.spawned.dt.month != 1
summer_minions = ((df_minions.spawned > datetime(2015,5,15)) &
                  (df_minions.spawned < datetime(2015,9,15))
name_endswith_y = df_minions.name.str.endswith('y')