Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

How to calculate number of weekes based on date in DataFrame Python Pandas?

I have DataFrame like below:

df = pd.DataFrame({"data" : ["25.01.2020", and many more other dates...]})
df["data"] = pd.to_datetime(df["data"], format = "%d%m%Y")

And I have a series of special dates like below:

special_date = pd.Series(pd.to_datetime(["16.01.2020",
                                         "27.01.2020",
                                         and many more other dates...], dayfirst=True))

And I need to calculate 2 more columns in this DataFrame:
col1 = number of weeks to the next special date
col2 = number of weeks after las special date

So I need results like below:
col1 = 1 because next special date after 25.01 is 27.01 so it is the same week
col2 = 2 because last special date before 25.01 is 16.01 so i is 2 weeks ago

*please be aware that I have many more dates, so code needs to work for more dates than only 2 special dates or only 1 data from df.

enter image description here

**I tried below code, but it calculate bad (give bad results):

delta = (s.to_numpy()[:,None] - df['data'].to_numpy()).astype('timedelta64[D]')  / np.timedelta64(1, 'D')
n = np.min( delta, 0, where=delta> 0, initial=np.inf)
p = np.min(-delta, 0, where=delta<=0, initial=np.inf)

df['next'] = np.ceil(n/7) #consider np.floor
df['prev'] = np.ceil(p/7) 
question from:https://stackoverflow.com/questions/65839726/how-to-calculate-number-of-weekes-based-on-date-in-dataframe-python-pandas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...