在Python系列中按月拆分数据帧

时间:2018-11-15 15:53:00

标签: python python-3.x python-2.7 pandas dataframe

我的数据框的日期范围为每组1-12个月。数据如下:

     Date         AB      AK      AR      DC
  0  2005-01-01  267724 37140   152536  60004
  1  2005-02-01  214444 32710   149821  49280
  2  2005-03-01  205938 27484   141526  41345
  3  2005-04-01  99262  14562   81254   31609
  4  2005-05-01  66059  8172    50241   18705
  5  2005-06-01  33556  4880    27216   11796
  6  2005-07-01  28057  4138    20156   9126
  7  2005-08-01  25466  3892    19005   8262
  8  2005-09-01  26819  3923    18776   9480
  9  2005-10-01  60849  5942    31255   1664
.
.

日期采用datetime格式:

data_res_num.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 164 entries, 0 to 163
Data columns (total 11 columns):
Date                   164 non-null datetime64[ns]

但是当我尝试通过以下方式仅通过某些月份(10到3个月)时:

df = df.loc[(df['Date'].dt.month > 10) & (df['Date'].dt.month < 4)]

我得到df的空白帧。

我以为它可能是这个范围,但是即使我将==设置为某个月,它也会给我一个空白框。

如何选择11月至3月的范围?

1 个答案:

答案 0 :(得分:1)

尝试不使用.loc进行切片:

df = df[(df['Date'].dt.month > 10) | (df['Date'].dt.month < 4)] 
相关问题