“str”对象没有属性“isocalendar”

2024-09-30 06:18:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'。我怎样才能修好它


Tags: 数据lambdaname消息dfdateobject错误
1条回答
网友
1楼 · 发布于 2024-09-30 06:18:50

这就是错误所在,您的“日期”列当前是对象,因此请将其转换为datetime:

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

相关问题 更多 >

    热门问题