I have a pandas dataframe and want to turn all the dates into the last date of the previous month. For example "2020-02-04" should turn into "2020-01-31", "2020-03-03" should turn into "2020-02-28" and so on. My df looks like this (in the month column I already have the right month for my wanted date) :
In[76]: dfall[["date", "month"]]
Out[76]:
date month
0 2020-02-04 1
1 2020-03-03 2
2 2020-04-02 3
3 2020-05-05 4
4 2020-06-03 5
5 2020-07-02 6
Now I tried this:
import calendar
import datetime
today = datetime.now()
dfall.date = str(today.year) + "-" + str(dfall.month) + "-" + str(calendar.monthrange(today.year,dfall.month)[1])
The idea was to build the new date by adding the strings together. But this code raises an error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I know the error is coming from this part: str(calendar.monthrange(today.year,dfall.month)[1])
(without this part the codes runs without error but the result is not what I want). It's probably because python doesnt know which month to take from dfall.month
. Does anybody know how I could handle that problem?