I have a pandas DataFrame with index column = date
.
Input:
value date 1986-01-31 22.93 1986-02-28 15.46
I want to floor the date to the first day of that month
Output:
value date 1986-01-01 22.93 1986-02-01 15.46
What I tried:
df.index.floor('M') ValueError: <MonthEnd> is a non-fixed frequency
This is potentially because the df is generated by df = df.resample("M").sum()
(The output of this code is the input at the beginning of the question)
I also tried df = df.resample("M", convention='start').sum()
. However, it does not work.
I know in R, it is easy to just call floor(date, 'M')
.
To get the first day of the month using Python, the easiest way is to create a new date with datetime. date() and pass “1” as the third argument.
there is a pandas issue about the floor problem
the suggested way is
import pandas as pd pd.to_datetime(df.date).dt.to_period('M').dt.to_timestamp()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With