[英]filter pandas dataframe by function on index
I have a dataframe with a Date used as index, I would like to extract all rows that are for a given month say January. 我有一个使用日期作为索引的数据框,我想提取给定月份(例如一月)的所有行。 Eg given
给定
Date Col1
2000-01-01 1
...
2000-12-31 12
2001-01-01 1
...
2001-12-31 12
2002-01-01 1
...
2002-12-31 12
then this works 然后这有效
f = df.index.map(lambda x: x.month==1)
new_df = df[f]
Is there a simpler way of getting new_df? 有没有更简单的方法来获取new_df?
I would have expected to be able to do something like df.loc[lambda x: x.month==1]
but this does not work because x
is actually df
(which is counter-intuitive as .loc
expect actual labels in all other forms of .loc
calls so I would have though x
would be each label of the index). 我本来希望能够执行类似
df.loc[lambda x: x.month==1]
但是这并不起作用,因为x
实际上是df
(因为.loc
期望在所有其他标签中都使用实际标签,这是违反直觉的.loc
调用的形式,因此尽管x
将是索引的每个标签)。 Or df.filter(lambda x: x.month==1)
but filter
does not accept a callback. 或
df.filter(lambda x: x.month==1)
但filter
不接受回调。
You can use pandas.DatetimeIndex.month
with loc
to return index where condition matches 您可以使用
pandas.DatetimeIndex.month
用loc
来回报指数,其中条件匹配
df.loc[df.index.month==1]
#df[df.index.month==1]
Col1
Date
2000-01-01 1.0
2001-01-01 1.0
2002-01-01 1.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.