Python 熊猫:选择具有特定月份和日期的所有日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28569461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: select all dates with specific month and day
提问by user3439329
I have a dataframe full of dates and I would like to select all dates where the month==12 and the day==25 and add replace the zero in the xmas
column with a 1.
我有一个充满日期的数据框,我想选择月==12和日==25的所有日期,并添加用xmas
1替换列中的零。
Anyway to do this? the second line of my code errors out.
无论如何要做到这一点?我的代码的第二行出错了。
df = DataFrame({'date':[datetime(2013,1,1).date() + timedelta(days=i) for i in range(0,365*2)], 'xmas':np.zeros(365*2)})
df[df['date'].month==12 and df['date'].day==25] = 1
回答by EdChum
Basically what you tried won't work as you need to use the &
to compare arrays, additionally you need to use parentheses due to operator precedence. On top of this you should use loc
to perform the indexing:
基本上您尝试的方法不起作用,因为您需要使用&
来比较数组,此外,由于运算符优先级,您还需要使用括号。最重要的是,您应该使用它loc
来执行索引:
df.loc[(df['date'].month==12) & (df['date'].day==25), 'xmas'] = 1
回答by Shayan RC
Pandas Series
with datetime now behaves differently. See .dt accessor.
Series
带有日期时间的Pandas现在表现不同。请参阅.dt 访问器。
This is how it should be done now:
现在应该这样做:
df.loc[(df['date'].dt.day==25) & (cust_df['date'].dt.month==12), 'xmas'] = 1