'str' 对象没有属性 'isocalendar'

'str' object has no attribute 'isocalendar'

我有以下问题。 我的数据集中有一列日期:

df["Date"].head()
0    2021-05-27
1    2021-05-27
2    2021-05-27
3    2021-05-27
4    2021-05-27
Name: Date, dtype: object

我需要计算一年中的第几周。我尝试使用此公式:df["date_week"] = df["Date"].apply(lambda x: x.isocalendar()[1]),但收到此错误消息:AttributeError: 'str' object has no attribute 'isocalendar'。请问我该如何解决?

这就是说您的 'Date' 列当前是对象的错误,因此请将其转换为日期时间:

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

最后:

df["date_week"]=df['Date'].dt.isocalendar().week
#you can also use: df['Date'].dt.week but it will give you FutureWarning