0

I have a dataset that has a column named "date_col". date_col has 1000+ dates, and the dates are only: 01/01/2011 and 01/01/2012.

This is what I tried:

table['date_col'] = pd.date_range(start='3/1/2011', 
                                  periods=len(table['date_col']), freq='d') 

How can I easily change the months to be something else than just 01/01?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Could you please add some code that you have written and tried? – Rahul P Dec 17 '19 at 20:22
  • table['date_col'] = pd.date_range(start = '3/1/2011', periods=len(table['date_col']), freq='d') – mpythonask Dec 17 '19 at 20:37
  • I do not want to change anything else in the table. That code will change the year too. I only want to change the month and days. – mpythonask Dec 17 '19 at 20:38
  • Does this answer your question? [Add months to a date in Pandas](https://stackoverflow.com/questions/46741423/add-months-to-a-date-in-pandas) – r.ook Dec 17 '19 at 21:11
  • What would you like i.e. `01/01` changed into? – martineau Dec 17 '19 at 21:31
  • anything but 01/01 – mpythonask Dec 17 '19 at 21:32
  • yes r.ook that answered the question with a little tweak. Here is the code: table['date_col'] = table['date_col'] + pd.DateOffset(months = 2) – mpythonask Dec 17 '19 at 21:48
  • oh, it still just change the dates to the same dates. It is not randomly incrementing it tho! so the date would be 3/1/2011 and 3/1/2012. It would be nice to have different months and days randomly in each column. – mpythonask Dec 17 '19 at 22:07

1 Answers1

0

You can parse the date column into a datetime object so you can manipulate it easily, something like this should work:

from datetime import datetime

date_str = '01/01/2012'
date_format = '%d/%m/%Y'
date = datetime.strptime(date_str, date_format)

# just change the day
date = date.replace(day=2)
marcos
  • 4,473
  • 1
  • 10
  • 24
  • I have already tried that by incrementing it with weeks, but it will also change the year. I do not want to change the year. I only need to change the months and day. The years should be the same. I need to keep the year as is and change the months and days. date_str = '2012/01/01' date_format = '%Y/%m/%d' date = datetime.strptime(date_str, date_format) next_day = timedelta(weeks=1) + date table['date_col'] = next_day.strftime(date_format) – mpythonask Dec 17 '19 at 20:59
  • If you only want to change the day without changing the year or the month now it should work. – marcos Dec 17 '19 at 21:03