Keyan H
Keyan H

Reputation: 37

Create a new column in a dataframe that shows Day of the Week from an already existing dd/mm/yy column? Python

I have a dataframe that contains a column with dates e.g. 24/07/15 etc Is there a way to create a new column into the dataframe that displays all the days of the week corresponding to the already existing 'Date' column?

I want the output to appear as: [Date][DayOfTheWeek]

Upvotes: 1

Views: 375

Answers (3)

Mayank Porwal
Mayank Porwal

Reputation: 34046

This might work:

If you want day name:

In [1405]: df                                                                                                                                                                                               
Out[1405]: 
      dates
0  24/07/15
1  25/07/15
2  26/07/15    

In [1406]: df['dates'] = pd.to_datetime(df['dates']) # You don't need to specify the format also.                                                                                                                                                      

In [1408]: df['dow'] = df['dates'].dt.day_name()                                                                                                                                                            

In [1409]: df                                                                                                                                                                                               
Out[1409]: 
       dates       dow
0 2015-07-24    Friday
1 2015-07-25  Saturday
2 2015-07-26    Sunday

If you want day number:

In [1410]: df['dow'] = df['dates'].dt.day                                                                                                                                                                   

In [1411]: df                                                                                                                                                                                               
Out[1411]: 
       dates  dow
0 2015-07-24   24
1 2015-07-25   25
2 2015-07-26   26

Upvotes: 1

Renaud
Renaud

Reputation: 2819

Depending of the type of you column Date.

df['Date']=pd.to_datetime(df['Date'], format="d/%m/%y") 
df['weekday'] = df['Date'].dt.dayofweek

Upvotes: 0

DanielDavies
DanielDavies

Reputation: 56

I would try the apply function, so something like this:

def extractDayOfWeek(dateString):
    ...

df['DayOfWeek'] = df.apply(lambda x: extractDayOfWeek(x['Date'], axis=1)

The idea is that, you map over every row, extract the 'date' column, and then apply your own function to create a new row entry named 'Day'

Upvotes: 0

Related Questions