Make conditional changes to numerous dates

Viewed 40

I'm sure this is really easy to answer but I have only just started using Pandas.

I have a column in my excel file called 'Day' and a Date/time column called 'Date'.

I want to update my Day column with the corresponding day of NUMEROUS Dates from the 'Date' column.

So far I use this code shown below to change the date/time to just date

df['Date'] = pd.to_datetime(df.Date).dt.strftime('%d/%m/%Y')

And then use this code to change the 'Day' column to Tuesday

df.loc[df['Date'] == '02/02/2018', 'Day'] = '2'

(2 signifies the 2nd day of the week)

This works great. The problem is, my excel sheet has 500000+ rows of data and lots of dates. Therefore I need this code to work with numerous dates (4 different dates to be exact)

For example; I have tried this code;

df.loc[df['Date'] == '02/02/2018' + '09/02/2018' + '16/02/2018' + '23/02/2018', 'Day'] = '2'

Which does not give me an error, but does not change the date to 2. I know I could just use the same line of code numerous times and change the date each time...but there must be a way to do it the way I explained? Help would be greatly appreciated :)

2 Answers

2/2/2018 is a Friday so I don't know what "2nd day in a week" mean. Does your week starts on Thursday?

Since you have already converted day to Timestamp, use the dt accessor:

df['Day'] = df['Date'].dt.dayofweek()

Monday is 0 and Sunday = 6. Manipulate that as needed.

If got it right, you want to change the Day column for just a few Dates, right? If so, you can just include these dates in a separated list and do

my_dates = ['02/02/2018', '09/02/2018', '16/02/2018', '23/02/2018']
df.loc[df['Date'].isin(my_dates), 'Day'] = '2'
Related