日期与该月的第一个日期相差多少? [英] How floor a date to the first date of that month?

查看:117
本文介绍了日期与该月的第一个日期相差多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有索引列= date 的pandas DataFrame。

I have a pandas DataFrame with index column = date.

输入:

            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

输出:

            value
date    
1986-01-01  22.93
1986-02-01  15.46

我尝试了什么:

df.index.floor('M')
ValueError: <MonthEnd> is a non-fixed frequency

这可能是因为df是由
<$生成的c $ c> df = df.resample( M)。sum()(此代码的输出是问题开头的输入)

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)

我也尝试了 df = df.resample( M,Convention ='start')。sum()。但是,它不起作用。

I also tried df = df.resample("M", convention='start').sum(). However, it does not work.

我在R中知道,只需调用 floor(date,'M')

I know in R, it is easy to just call floor(date, 'M').

推荐答案

有一个关于地板问题的熊猫问题

建议的方法是

import pandas as pd
pd.to_datetime(df.date).dt.to_period('M').dt.to_timestamp()

这篇关于日期与该月的第一个日期相差多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆