熊猫:选择带有特定月份和日期的所有日期
问题描述:
我有一个充满日期的数据框,我想选择month == 12和day == 25的所有日期,并在xmas
列中将零替换为1.
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.
是否仍然要执行此操作?我的代码的第二行错误了.
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
答
带有日期时间的熊猫Series
现在的行为有所不同.参见 .dt访问器.
Pandas Series
with datetime now behaves differently. See .dt accessor.
现在应该这样做:
df.loc[(df['date'].dt.day==25) & (cust_df['date'].dt.month==12), 'xmas'] = 1