繁体   English   中英

熊猫-在自定义日期时间索引中返回当月的最后一天/第一天

[英]Pandas - Return last/first day of the month in a custom Datetime Index

我正在使用具有自定义日期(特定假日,工作日..)的多索引列数据框。

DatetimeIndex(['1989-01-31', '1989-02-01', '1989-02-02', '1989-02-03',
           '1989-02-06', '1989-02-07', '1989-02-08', '1989-02-09',
           '1989-02-10', '1989-02-13',
           ...
           '2019-02-25', '2019-02-26', '2019-02-27', '2019-02-28',
           '2019-03-01', '2019-03-04', '2019-03-05', '2019-03-06',
           '2019-03-07', '2019-03-08'],
          dtype='datetime64[ns]', length=7585, freq=None)

我需要从索引中将其切成当月的第一天或最后一天。 由于假期,...该月某月的某些第一天/最后一天与freq ='BM'不匹配。 不用说我不能使用resample(),...

这里是一个例子:

import pandas as pd
import numpy as np
idx = pd.DatetimeIndex(['1989-01-31', '1989-02-01', '1989-02-02', '1989-02-03','1989-02-06', '1989-02-07', '1989-02-08', '1989-02-09','1989-02-10', '1989-02-13', '2019-02-25', '2019-02-26', '2019-02-27', '2019-02-28','2019-03-01', '2019-03-04', '2019-03-05', '2019-03-06','2019-03-07', '2019-03-08'], dtype='datetime64[ns]')

numbers = [0, 1, 2]
colors = [u'green', u'purple']
col = pd.MultiIndex.from_product([numbers, colors],names=['number', 'color'])

df = pd.DataFrame(np.random.rand(len(idx),len(col)),index =idx,columns=col)
number            0                 1                 2         
color         green   purple    green   purple    green   purple
2018-06-05  0.64943  0.64943  0.64943  0.64943  0.64943  0.64943
etc...

预期产量:

2018-06-29  0.64943  0.64943  0.64943  0.64943  0.64943  0.64943

请问我该怎么做?

谢谢

您需要在DataFrame上使用Grouper 在上述问题中使用mcve:

# Month End
df.groupby(pd.Grouper(freq='M')).last()

# Month Start
df.groupby(pd.Grouper(freq='MS')).first()

注意:以这种方式分组的是DateTimeIndex月,该月的min和max月是日历行,不一定在索引中。

因此,我们可以按照自己的方式进行分组,需要注意多年来重复的几个月。

grpr = df.groupby([df.index.year, df.index.month])
data = []
for g, gdf in grpr:
    data.append(gdf.loc[gdf.index.min()])
    data.append(gdf.loc[gdf.index.max()])

new_df = pd.DataFrame(data)
new_df
number             0                   1                   2          
color          green    purple     green    purple     green    purple
1989-01-31  0.246601  0.915123  0.105688  0.645864  0.845655  0.339800
1989-01-31  0.246601  0.915123  0.105688  0.645864  0.845655  0.339800
1989-02-01  0.694509  0.665852  0.593890  0.715831  0.474022  0.011742
1989-02-13  0.770202  0.452575  0.935573  0.554261  0.235477  0.475279
2019-02-25  0.626251  0.826958  0.617132  0.118507  0.079782  0.183616
2019-02-28  0.740565  0.131821  0.968403  0.981093  0.211755  0.806868
2019-03-01  0.812805  0.379727  0.758403  0.345361  0.908825  0.166638
2019-03-08  0.238481  0.045592  0.740523  0.201989  0.432714  0.672510

看到重复是正确的,因为gdf.index.min()可能等于gdf.index.max() 遍历组时,检查将消除重复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM