首页 > 解决方案 > 从 pandas 日期时间列中提取唯一的月度周期

问题描述

我有一个这样的日期列。

2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-28
2012-01-29
2012-01-29
2012-01-29
2012-01-29
2012-01-29
2012-01-29

....
2016-12-31
2016-12-31
2016-12-31
2016-12-31

我想将其转换为以下任何格式:即获取唯一的 yyyy-mm

2012-01  or 2012-Jan   or Jan
2012-02  or 2012-Feb   or Feb
2012-03 
...
2016-12   or 2012-Dec  or Dec

标签: pythonpandasdatetime

解决方案


使用DatetimeIndex.to_period

pd.DatetimeIndex(df['date']).to_period('M').unique()
#  PeriodIndex(['2012-01', '2016-12'], dtype='period[M]', name='date', freq='M')

如果需要月份名称,请使用strftime

df['date'].dt.strftime('%Y-%b').unique()
# array(['2012-Jan', '2016-Dec'], dtype=object)

如果需要 Series 格式,请使用drop_duplicates

df['date'].dt.strftime('%Y-%b').drop_duplicates()

0     2012-Jan
18    2016-Dec
Name: date, dtype: object

推荐阅读