Python 从DatetimeIndex中删除天数

Python 从DatetimeIndex中删除天数,python,pandas,datetime,Python,Pandas,Datetime,我使用的数据集只有年份月份的日期时间信息:20110003->2011-03。为了保留2011-03年的格式,我做了以下工作: #change 20110003 -> 2011-03 indicator_ccgs_re=indicator_ccgs.loc[:,'Time period Sortable'].astype(str) old_pattern='00' new_pattern='-' new_dates=[]

我使用的数据集只有年份月份的日期时间信息:20110003->2011-03。为了保留2011-03年的格式,我做了以下工作:

#change 20110003 -> 2011-03 
        indicator_ccgs_re=indicator_ccgs.loc[:,'Time period Sortable'].astype(str)
        old_pattern='00'
        new_pattern='-'
        new_dates=[]
        for i, v in indicator_ccgs_re.items():
            new_date = re.sub(old_pattern,new_pattern, v)
            new_dates=new_dates+[new_date]
        new_index=pd.to_datetime(new_dates,format='%Y%m%')
        values_period=indicator_ccgs.loc['2012-01':'2012-06','Value']
        type(new_index)
pandas.core.index.datetimes.DatetimeIndex

values_period.index

DatetimeIndex(['2012-01-01', '2012-02-01', '2012-03-01', '2012-04-01',
               '2012-05-01', '2012-06-01'],
              dtype='datetime64[ns]', freq=None)
因此,即使我指定了格式=“%Y%m%”,当天仍然存在

绘制时,数值为每月一次,但表格输出仍保留索引中的天数

我试着重新取样

monthly=values_period.resample('M').sum()
monthly.index
但天数仍然存在(仅最后一天,而不是第一个月):

并尝试:

dt=new_index.strptime('%Y-%m')
我得到了AttributeError:“DatetimeIndex”对象没有属性“strTime”

是否有其他方法可以将当天从索引中移除

这应该会有帮助

import pandas as pd
df = pd.DataFrame({"a": ["20110003"]})
df["b"] = pd.to_datetime(df["a"], format='%Y00%m').apply(lambda x: x.strftime('%Y-%m'))
print(df["b"])
输出:

0    2011-03
Name: b, dtype: object

一个简单的方法是重置索引,然后使用lambda strftime,最后以新的datetime格式再次设置索引,即

   monthly = monthly.reset_index()
   monthly['date'] = monthly['date'].apply(lambda x: x.strftime('%Y-%m'))
   monthly.set_index('date', inplace=True)

谢谢拉凯什。这对于获取年-月序列很有效,但是类型是pandas.core.series.series,而不是pandas.core.index.datetimes.DatetimeIndex。我可以使用它对数据帧进行索引和切片,但在打印时,我不会将日期作为坐标。我不明白strftime为什么不提供DatetimeIndex。
   monthly = monthly.reset_index()
   monthly['date'] = monthly['date'].apply(lambda x: x.strftime('%Y-%m'))
   monthly.set_index('date', inplace=True)