从 Pandas DatetimeIndex 中删除天数

Ron*_*mon 2 python datetime pandas

我正在使用仅具有年月日期时间信息的数据集: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'

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

小智 7

一种直接的方法是重置索引,然后使用 lambda strftime,最后以新的日期时间格式再次设置索引,即

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


Rak*_*esh 1

这应该有帮助。

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"])
Run Code Online (Sandbox Code Playgroud)

输出:

0    2011-03
Name: b, dtype: object
Run Code Online (Sandbox Code Playgroud)