从熊猫数据框中提取3个月的块

时间:2016-05-25 10:22:39

标签: pandas

我必须从具有历史价值的熊猫数据框中提取3个月的块。我发现我可以用非常繁重的方式完成它(RX是数据对象,数据帧):

DateTimeI = pd.DatetimeIndex(RX.iloc[:,0]) # Creating the DatetimeIndex
Block_2015_1a = RX.iloc[DateTimeI.year == 2015, :] # Selecting all the records from 2015
DT_1a = pd.DatetimeIndex(Block_2015_1a.iloc[:,0]) # Creating the new DatetimeIndex
Block_2015_1a = Block_2015_1a.iloc[DT_1a.month <= 3, :] # Selecting all the records for the months 1 to 3.

当我在不同年份需要数月时,这种方式不会直接起作用。在Matlab(我正在从Matlab到Python的过渡)中,同样的任务可以优雅地完成:

Block_2015_1a = RX(RX.Date.Year == 2015 & RX.Date.Month <= 3, :);

是否有类似的方法与熊猫一起做?感谢

1 个答案:

答案 0 :(得分:0)

你可以使用矢量化.dt定位器,它可以提取日期时间的不同部分:

RX.loc[(RX.Date.dt.year == 2015) & (RX.Date.dt.month <= 3), :]