Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: select all dates with specific month and day

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
like image 413
user3439329 Avatar asked Feb 17 '15 19:02

user3439329


2 Answers

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

This is how it should be done now:

df.loc[(df['date'].dt.day==25) & (cust_df['date'].dt.month==12), 'xmas'] = 1
like image 125
Shayan RC Avatar answered Oct 16 '22 18:10

Shayan RC


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:

df.loc[(df['date'].month==12) & (df['date'].day==25), 'xmas'] = 1
like image 42
EdChum Avatar answered Oct 16 '22 20:10

EdChum