0

I have a pandas dataframe which has dates in the format YYYYMMDD stored as a float32. Is it possible to somehow calculate what day of the week each day is? Eg. monday = 1, tuesday =2, etc?

I don't even know where to start.

lara_toff
  • 413
  • 2
  • 14
  • 2
    Does this answer your question? [Create a day-of-week column in a Pandas dataframe using Python](https://stackoverflow.com/questions/30222533/create-a-day-of-week-column-in-a-pandas-dataframe-using-python) – snwflk Jan 11 '21 at 22:38
  • 1
    No since I get the following error: AttributeError: Can only use .dt accessor with datetimelike values – lara_toff Jan 11 '21 at 22:44

1 Answers1

1

We can convert the column to str first, then to datetime and use .dt.weekday:

df = pd.DataFrame({'date': [20210101, 20210102]})
df['weekday'] = pd.to_datetime(df['date'].astype(str)).dt.weekday

df

Output:

       date  weekday
0  20210101   4     
1  20210102   5     

P.S. Here Monday = 0, ..., Sunday = 6, so if you want 1-7 instead, you can add 1 to column values

perl
  • 9,826
  • 1
  • 10
  • 22