小编Ron*_*mon的帖子

从 Pandas DatetimeIndex 中删除天数

我正在使用仅具有年月日期时间信息的数据集: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)
Run Code Online (Sandbox Code Playgroud)

pandas.core.indexes.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)
Run Code Online (Sandbox Code Playgroud)

因此,即使我指定了 format='%Y%m%',这一天仍然存在。

绘制值是每月但表格输出仍保留索引中的天数。

我尝试重新采样

monthly=values_period.resample('M').sum()
monthly.index
Run Code Online (Sandbox Code Playgroud)

但天数仍然存在(仅最后一天而不是第一个月的一天):

DatetimeIndex(['2012-01-31', '2012-02-29', '2012-03-31', '2012-04-30',
               '2012-05-31', '2012-06-30'],
              dtype='datetime64[ns]', freq='M')
Run Code Online (Sandbox Code Playgroud)

并尝试:

dt=new_index.strptime('%Y-%m')
Run Code Online (Sandbox Code Playgroud)

我得到了 AttributeError: 'DatetimeIndex' object has no attribute 'strptime'

从索引中删除日期的任何其他解决方案?

python datetime pandas

2
推荐指数
2
解决办法
9031
查看次数

标签 统计

datetime ×1

pandas ×1

python ×1