Pandas: select all dates with a specific month and day

I have a data file full of dates, and I would like to select all dates where month == 12 and day == 25, and add replace zero in the xmas column with 1.

Anyway to do this? second line of errors of my code.

 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 
+7
python pandas datetime
source share
2 answers

Basically, what you tried will not work, since you need to use & to compare arrays, in addition, you need to use parentheses due to operator precedence. In addition to this, you must use loc to perform indexing:

 df.loc[(df['date'].month==12) & (df['date'].day==25), 'xmas'] = 1 
+9
source share

Pandas Series with datetime now behaves differently. See . Dt accessor .

Here's how it should be done now:

 df.loc[(df['date'].dt.day==25) & (cust_df['date'].dt.month==12), 'xmas'] = 1 
+4
source share

All Articles