Pandas: change the day

I have a series in datetime format, and I need to change the day to 1 for each record. I thought of numerous simple solutions, but none of them work for me. So far, it actually only works

  • set series as index
  • The month and year of the request from the index
  • Restore a new time series using year, month and 1

It can't be that hard, can it? There is a start month, but unfortunately offset , which is useless here. It seems that there is no set() function for the method and even less functionality, while the series is the column and not (part) of the index itself.

The only related question was, but the trick used there is not applicable here.

+5
source share
1 answer

You can use .apply and datetime.replace , for example:

 import pandas as pd from datetime import datetime ps = pd.Series([datetime(2014, 1, 7), datetime(2014, 3, 13), datetime(2014, 6, 12)]) new = ps.apply(lambda dt: dt.replace(day=1)) 

gives:

 0 2014-01-01 1 2014-03-01 2 2014-06-01 dtype: datetime64[ns] 
+9
source

Source: https://habr.com/ru/post/1214773/


All Articles