如何过滤 pandas 的年份和季度 [英] How to filter on year and quarter in pandas
问题描述
我有一个 DataFrame,其中有一列类型为 datetime64[ns].我想过滤年份和季度.有关如何执行此操作的任何建议?
I have a DataFrame with a column of type datetime64[ns]. I want to filter on both year and quarter. Any suggestions on how to do this?
我已经尝试过这个繁琐的解决方案
I have tried this cumbersome solution
data = data[(pd.Series(pd.DatetimeIndex(data['MatCalID']).year).isin([2018]) & pd.Series(pd.DatetimeIndex(data['MatCalID']).quarter).isin([2,3]))]
为什么要采用这种复杂的解决方案?:
Why this complicated solution?:
- 必须使用 pd.DatetimeIndex 才能访问年"和季度"
- 必须使用pd.Series才能使用'isin'
不幸的是,我收到提供了不可对齐的布尔系列键"作为错误.
Unfortunately I get 'Unalignable boolean Series key provided' as an error.
有人知道怎么做吗?
推荐答案
如果您运行的是 0.15.0
或更高版本的 Pandas,则没有必要将系列转换为 DateTimeIndex
因为现在有一个新的日期时间属性 .dt
.您可以使用它来访问日期时间对象的年份和季度属性,并使用布尔条件来过滤 df:
If you're running pandas version 0.15.0
or higher it is not necessary to cast the Series to a DateTimeIndex
as there is now a new datetime attribute .dt
. You can use this to access the year and quarter attributes of the datetime objects and use a boolean condition to filter the df:
data[(data['MatCalID'].dt.year == 2008) & (data['MatCalID'].dt.quarter.isin([2,3]))]
通常,当您想要测试多个值的成员资格而不是单个值时,您应该使用 isin
Normally you should be using isin
when you want to test membership of multiple values rather than a single value
这篇关于如何过滤 pandas 的年份和季度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!