【发布时间】:2016-11-29 04:49:20
【问题描述】:
我有一个名为“scores”的系列,带有一个日期时间索引。
我希望通过 quarter 和 year 对其进行子集化
伪代码:series.loc['q2 of 2013']
目前的尝试:s.dt.quarter
AttributeError: 只能使用带有 datetimelike 值的 .dt 访问器
s.index.dt.quarter
AttributeError: 'DatetimeIndex' 对象没有属性 'dt'
这很有效(灵感来自this answer),但我不敢相信这是在 Pandas 中执行此操作的正确方法:
d = pd.DataFrame(s)d['date'] = pd.to_datetime(d.index)d.loc[(d['date'].dt.quarter == 2) & (d['date'].dt.year == 2013)]['scores']
我希望有一种方法可以做到这一点,而无需转换为数据集,将索引强制转换为日期时间,然后从中获取系列。
我缺少什么,在 Pandas 系列中执行此操作的优雅方式是什么?
【问题讨论】:
-
如果索引是日期时间
s.index.quarter,这将起作用。 -
你想要一个可以在特定年份和季度获得的函数吗?
-
IIUC 你需要
scores.ix[scores.index.quarter==2]. -
@shivsn 有正确的答案,我很震惊我没想过放弃
dt的事情。
标签: python datetime pandas datetimeindex