python - 从 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
解决方案
使用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
推荐阅读
- javascript - 为什么没有将局部函数分配给全局对象(窗口)?
- python - 如何需要两个 jsonschema 属性之一,但还要设置默认值?
- reactjs - Material-UI 样式和 html/markdown
- visual-studio-code - 使用 Atmel-Ice 在 Visual Studio Code 中调试 Arduino Due
- ruby - 如何制作一个 Ruby 方法来制作具有“n”宽度的星号钻石?
- python - 使精灵在点击时消失
- sql - 通过在 Hive/Athena 的 CSV 文件中添加两列来创建外部表
- android - 深度链接在 chrome expo react native 项目中不起作用
- python - 在 MacOS Big Sur 上安装 Python3.4 时出错
- powershell - 创建 NotifyIcon 并使用 powershell 处理单击事件