如何按特定的月份/日期筛选数据框?

32

因此,我的代码如下:

df['Dates'][df['Dates'].index.month == 11]

我在进行一个测试,试图筛选只显示11月份的日期,但是这并没有起作用。它给我返回了以下错误:AttributeError: 'Int64Index' object has no attribute 'month'。

如果我执行以下操作:

print type(df['Dates'][0])

然后我得到了类 'pandas.tslib.Timestamp',这让我相信数据帧中存储的对象类型是时间戳对象。(我不确定出现错误之前的 'Int64Index' 是从哪里来的...)

我想要做的是:数据帧列包含2000年代初至今以以下格式表示的日期:dd/mm/yyyy。我想过滤仅位于11月15日至3月15日之间的日期,与年份无关。最简单的方法是什么?

谢谢。

这是带有索引的df['Dates']:

0    2006-01-01
1    2006-01-02
2    2006-01-03
3    2006-01-04
4    2006-01-05
5    2006-01-06
6    2006-01-07
7    2006-01-08
8    2006-01-09
9    2006-01-10
10   2006-01-11
11   2006-01-12
12   2006-01-13
13   2006-01-14
14   2006-01-15
...

请展示一下 df 的样子。你可能想要使用 df.set_index('Dates'),但是没有看到实际情况很难说。 - TomAugspurger
请编辑您的问题,加上 df 以使其格式正确。如果可以,请发布整个数据框的头部。 - TomAugspurger
3个回答

66

使用pd.to_datetimedt访问器

所接受的答案不是处理这个问题的“pandas”方式。使用dt访问器选择仅包含11月的行:

# df['Date'] = pd.to_datetime(df['Date']) -- if column is not datetime yet
df = df[df['Date'].dt.month == 11]
同样适用于天数或年份,你可以用dt.daydt.year替换dt.month。 此外还有许多其他选项,这里列出了其中一些: dt.quarter dt.week dt.weekday dt.day_name dt.is_month_end dt.is_month_start dt.is_year_end dt.is_year_start 要查看完整列表,请参阅文档

1
这种方法对于旧日期不起作用,例如 OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1031-11-29 00:00:00。对于这样的数据,您必须使用一些魔法。 - VMAtm

28

将一个匿名函数映射到系列上以计算月份,然后将其与11(代表11月)进行比较。这将给出一个布尔掩码。然后,您可以使用该掩码来过滤数据框。

nov_mask = df['Dates'].map(lambda x: x.month) == 11
df[nov_mask]

我认为没有一种直接的方法可以按照你想要的方式过滤掉年份,所以尝试这个方法。

nov_mar_series = pd.Series(pd.date_range("2013-11-15", "2014-03-15"))
#create timestamp without year
nov_mar_no_year = nov_mar_series.map(lambda x: x.strftime("%m-%d"))
#add a yearless timestamp to the dataframe
df["no_year"] = df['Date'].map(lambda x: x.strftime("%m-%d"))
no_year_mask = df['no_year'].isin(nov_mar_no_year)
df[no_year_mask]

int64实际上是因为首先使用df['Dates'].index.month访问了索引。在这种情况下,索引是一个Int64Index,它没有月份属性。 - TomAugspurger

4

您的代码中存在两个问题。首先,需要在筛选条件后引用列。其次,可以使用".month"与列或索引,但不能同时使用。以下其中一个应该可以解决问题:

df[df.index.month == 11]['Dates']

df[df['Dates'].month == 11]['Dates']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接