简体   繁体   中英

Calculation of days and weeks from some dates in DataFrame in Python Pandas?

I have DataFrame like below:

df = pd.DataFrame({"data" : ["11.01.2020", "05.02.2020", "01.03.2020"]})
df["data"] = df["data"].astype("datetime64")

And I have special dates like belo:

special_date = pd.to_datetime(["20.01.2020", "10.02.2020", "10.03.2020"], dayfirst=True)

And I need to add 4 columns to this data frame:

  • col1 = number of days until the next special data
  • col2 = number of weeks until the next special data
  • col3 = number of days after last special data
  • col4 = number of weeks afret last special data

So I need result like below: (I am not sure where I correctly calculated col2 and col4 about weekes)

在此处输入图像描述

You can use pandas date time function in this case. Here is a sample:

df["data"] = pd.to_datetime(df["data"], format = "%d%m%Y")

To calculate the number of days between two dates:

import pandas as pd
df = pd.DataFrame({"data" : ["11.01.2020", "05.02.2020", "01.03.2020"]})
df["data"]=pd.to_datetime(df["data"], dayfirst=True)

df["special_date"] = pd.to_datetime(["20.01.2020", "10.02.2020", "10.03.2020"], dayfirst=True)
df['C1'] = (df['special_date'] - df['data']).dt.days
df['C2']=((df['special_date'] - df['data']).dt.days)//7

This will give you:

        data special_date  C1  C2
0 2020-01-11   2020-01-20   9   1
1 2020-02-05   2020-02-10   5   0
2 2020-03-01   2020-03-10   9   1

Similarly you can find the number of weeks and days after special dates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM