首页 > 解决方案 > 将 period_range 转换为字符串列表

问题描述

我有这个

>>> start
'1905'
>>> end
'2003'
>>> p = pd.period_range(pd.to_datetime(start, format="%y%m"), pd.to_datetime(end, format="%y%m"), freq='M')
>>> p
PeriodIndex(['2019-05', '2019-06', '2019-07', '2019-08', '2019-09', '2019-10',
             '2019-11', '2019-12', '2020-01', '2020-02', '2020-03'],
            dtype='period[M]', freq='M')

我想将 p 转换为包含句点的字符串列表

>>> p
['1905', '1906', '1907', '1908', '1909', '1910', '1911', '1912', '2001', '2002', '2003']

字符串的格式很重要,它应该与 eg('yymm') 中所示的格式相同,有人可以帮助我干净地实现这一点吗?

标签: pythonpandasdatetime

解决方案


您可以使用PeriodIndex.strftimewith'%y%m'来表示“YYMM”格式:

p.strftime('%y%m')
# Index(['1905', '1906', '1907', '1908', '1909', '1910', '1911', '1912', '2001',
#        '2002', '2003'],
#       dtype='object')

推荐阅读