当月份不以 01 开头时,如何在 datetimeindex 中获取每个月的第一天?

How to get first day of each month in datetimeindex, when month doesn't starts with 01?

我有一个带 DateTimeIndex 的 DataFrame,10 年了,一天一天。我需要提取对应于每个月的第一天的行。然而,并非所有月份都以 01 开头,有些月份以 02、03、04 等开头。

2020-01-02
2020-01-03
...
2020-01-31
2020-02-03
...
2020-02-29
2020-03-02

预期的 df 必须是:

2020-01-02
2020-02-03
2020-03-02

有什么建议吗?

在月份的头几天使用 DatetimeIndex.to_period for months periods, then test duplicates by Index.duplicated and filter in boolean indexing 和倒置掩码:

#if necessary
df = df.sort_index()

print (df)
            A
date         
2020-01-02  4
2020-01-03  9
2020-01-31  2
2020-02-03  7
2020-02-29  3
2020-03-02  1

df1 = df[~df.index.to_period('m').duplicated()]
print (df1)
            A
date         
2020-01-02  4
2020-02-03  7
2020-03-02  1

详情:

print (df.index.to_period('m'))
PeriodIndex(['2020-01', '2020-01', '2020-01', '2020-02', '2020-02', '2020-03'], 
            dtype='period[M]', name='date', freq='M')

print (df.index.to_period('m').duplicated())
[False  True  True False  True False]

print (~df.index.to_period('m').duplicated())
[ True False False  True False  True]

另一个解决方案是使用 GroupBy.head:

df1 = df.groupby(df.index.to_period('m')).head(1)
print (df1)
            A
date         
2020-01-02  4
2020-02-03  7
2020-03-02  1

您可以像这样从日期中提取月份:

df["d"] = pd.to_datetime(df.d)
df["month"] = df.d.dt.month

df
           d  month
0 2020-01-02      1
1 2020-01-03      1
2 2020-01-31      1
3 2020-02-03      2
4 2020-02-29      2
5 2020-03-02      3

然后按月分组,取组中的第一个元素:

df.groupby("month").first()

               d
month           
1     2020-01-02
2     2020-02-03
3     2020-03-02