0

I would like to create a weekday column from a another column Date in dataframe df:

        id      timestamp               data    Date
27001   27242   2020-01-01 09:07:21.277 19.5    2020-01-01
27002   27243   2020-01-01 09:07:21.377 19.0    2020-01-01
27581   27822   2020-01-02 07:53:05.173 19.5    2020-01-02

with code

df['Date'] = pd.Series(df['Date'], dtype="string")

# df['Date'] = pd.Series(df['Date'], dtype=pd.StringDtype)
# df['Date'] = df['Date'].astype(str)
datetime.datetime.strptime(df['Date'], '%Y-%m-%d').strftime('%A')

based on these posts: post1 post2

but incurred error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-bd59bae0ddd9> in <module>()
      3 
      4 # df['Date'] = df['Date'].astype(str)
----> 5 datetime.datetime.strptime(df['Date'], '%Y-%m-%d').strftime('%A')
      6 # type(df['Date'])

TypeError: strptime() argument 1 must be str, not Series

What is the best way to create a "day of week" column from column Date?


Update:

Tried

df['Weekday'] = df['Date'].weekday

which returned

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-27-f788d4a4608d> in <module>()
      1 
----> 2 df['Weekday'] = df['Date'].weekday

/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py in __getattr__(self, name)
   5272             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5273                 return self[name]
-> 5274             return object.__getattribute__(self, name)
   5275 
   5276     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'weekday'

then tried

df['Weekday'] = df['Date'].dt.weekday

which returned

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-28-592865ef8c59> in <module>()
      1 
----> 2 df['Weekday'] = df['Date'].dt.weekday

2 frames
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/accessors.py in __new__(cls, data)
    336             return DatetimeProperties(data, orig)
    337 
--> 338         raise AttributeError("Can only use .dt accessor with datetimelike values")

AttributeError: Can only use .dt accessor with datetimelike values

Why is this happening?

nilsinelabore
  • 4,143
  • 17
  • 65
  • 122
  • 2
    `df['Weekday'] = pd.to_datetime(df['Date']).apply(lambda x: x.strftime('%A'))` – mechanical_meat Apr 02 '20 at 23:17
  • @VorsprungdurchTechnik thank you that worked, actually I would like to insert `weekday` in a plot title as of https://stackoverflow.com/q/60922726/11901732. Can I apply this solution in that question? – nilsinelabore Apr 02 '20 at 23:29
  • Oooh, yes that's an even better solution. Why did you ask this question then? – mechanical_meat Apr 02 '20 at 23:43
  • @VorsprungdurchTechnik That was the actual question I wanted to solve but got stuck. So had to step back and rethink about a different approach.. – nilsinelabore Apr 02 '20 at 23:46

2 Answers2

1

Your column df['Weekday'] isn't of type Datetime yet. Only then can you call the method .dt.

df['Date'] = pd.to_datetime(df['Date'])

should fix that.

gosuto
  • 5,422
  • 6
  • 36
  • 57
1

For the initial dataframe where datatype of Date column is str , you can do :

df['Weekday'] = pd.to_datetime(df['Date']).apply(lambda x : x.weekday())

Another way is :

df['Weekday'] =  pd.to_datetime(df['date']).dt.weekday
Spandan Brahmbhatt
  • 3,774
  • 6
  • 24
  • 36