Я хотел бы создать weekday
столбец из другого столбца Date
в фрейме данных 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
с кодом
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')
на основе этих сообщений : post1 post2
но произошла ошибка:
---------------------------------------------------------------------------
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
Каков наилучший способ создания столбца "day of week"
из столбца Date
?
Обновление:
Попробовал
df['Weekday'] = df['Date'].weekday
, который вернул
---------------------------------------------------------------------------
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'
, затем попытался
df['Weekday'] = df['Date'].dt.weekday
который вернулся
---------------------------------------------------------------------------
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
Почему это происходит?