使用 Python 获取列中的周数

发布于 2025-01-19 14:20:32 字数 715 浏览 0 评论 0原文

我试图根据数据在数据范围内使用一周的数字,根据数据中的几天,一个月的时间里有一周的数字。 这是以下代码 -

import pandas as pd
import numpy as np
s={'yr':[2014,2014,2014,2014,2015,2015,2015,2015],'Month':['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug'],'Days':[12,24,11,22,10,15,22,3]}
p=pd.DataFrame(data=s)

”在此处输入图像描述”

import datetime
p['week']=datetime.date(p['yr'], p['Month'], p['Days']).isocalendar().week

I am getting the below error-
TypeError: cannot convert the series to <class 'int'>

我不确定如何解决此错误,我认为我也需要以数字格式转换月份还日期吗?

I was trying to get this requirement where I want to have a column in my dataframe with week number, based on Days, Month an yr present in data.
Here is the below code-

import pandas as pd
import numpy as np
s={'yr':[2014,2014,2014,2014,2015,2015,2015,2015],'Month':['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug'],'Days':[12,24,11,22,10,15,22,3]}
p=pd.DataFrame(data=s)

enter image description here

import datetime
p['week']=datetime.date(p['yr'], p['Month'], p['Days']).isocalendar().week

I am getting the below error-
TypeError: cannot convert the series to <class 'int'>

I am not sure on how to resolve this error, I think I need to convert Month in numeric format too, how would be able to do this and get the week number in the date also?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

春花秋月 2025-01-26 14:20:32

这条线并不那么好,但它有效:

p['week'] = [datetime.datetime.strptime(str(p['yr'][i])+p['Month'][i]+str(p['Days'][i]), '%Y%b%d').isocalendar()[1] for i in range(len(p))]

This line isn't as nice, but it works:

p['week'] = [datetime.datetime.strptime(str(p['yr'][i])+p['Month'][i]+str(p['Days'][i]), '%Y%b%d').isocalendar()[1] for i in range(len(p))]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文