Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How floor a date to the first date of that month?

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').

like image 969
Jill Clover Avatar asked Feb 16 '17 21:02

Jill Clover


People also ask

How do you get to the beginning of the month in Python?

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.


1 Answers

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() 
like image 86
Deo Leung Avatar answered Oct 08 '22 05:10

Deo Leung