1

In the previous solution I have obtained a column "from" in the date format - 20190101. I need to add the column "to" based on the column "from". Basically the range is like this:

from 20190101 to 20190114

from 20190115 to 20190131

from 20190201 to 20190215

from 20190215 to 20190228

etc

How can I automatize this?

How to treat data as dates and operate on them. Eg., I have a date 20181231, I want to add a day 20181231 + 1 = 20190101

1
  • Is input data column from ? Commented Oct 25, 2019 at 8:45

2 Answers 2

2

Assuming your data are those from the linked question:

df = pd.DataFrame({'id': {1: 'id_2', 2: 'id_3', 3: 'id_4', 4: 'id_5', 0: 'id_1'},
                   'price': {1: 24.5, 2: 17.5, 3: 149.5, 4: 7.5, 0: 7.5},
                   'code': {1: 'r', 2: 'r', 3: 'c', 4: 'r', 0: 'r'},
                   'from': {1: 20190115, 2: 20190101, 3: 20190115, 4: 20190115, 0: 20190115}})

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

df["to"] = df["from"]+pd.DateOffset(days=14)

print (df)

#
     id  price code       from         to
1  id_2   24.5    r 2019-01-15 2019-01-29
2  id_3   17.5    r 2019-01-01 2019-01-15
3  id_4  149.5    c 2019-01-15 2019-01-29
4  id_5    7.5    r 2019-01-15 2019-01-29
0  id_1    7.5    r 2019-01-15 2019-01-29
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you @Henry Yik. Is it possible to change a format to 20190101 in the final version. Or it's not a date format but just a string?
It’s a dtype of datetime but you can use strftime to construct your desired format by Series.dt.strftime(“%Y%m%d”).
I have a question - for the second fortnight of each month it's important that the column "to" is filled with the last day of the month which is not happening for February. Ho to fix it?
df["to"] = df["from"]+pd.offsets.MonthEnd() to get the last day of a month.
1

As in your example

df:    
        from
0 2019-01-01
1 2019-01-15
2 2019-02-01
3 2019-02-15

You need subtract 1 day from column from and shift backward and fillna

df['to'] = ((df['from'] - pd.DateOffset(1)).shift(-1)
                                           .fillna(df['from'].tail(1) + 
                                                   pd.offsets.MonthEnd(0)))

Out[753]:
        from         to
0 2019-01-01 2019-01-14
1 2019-01-15 2019-01-31
2 2019-02-01 2019-02-14
3 2019-02-15 2019-02-28

1 Comment

Great @Andy L! Exactly what I need. It works for months like February with 28 days.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.