nilsinelabore
nilsinelabore

Reputation: 5145

Convert dataframe column to string to apply strftime

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?

Upvotes: 0

Views: 3813

Answers (2)

gosuto
gosuto

Reputation: 5741

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.

Upvotes: 1

Spandan Brahmbhatt
Spandan Brahmbhatt

Reputation: 4064

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

Upvotes: 1

Related Questions