首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Pandas中将year-date转换为year-quarter

在Pandas中将year-date转换为year-quarter
EN

Stack Overflow用户
提问于 2020-05-04 21:38:14
回答 2查看 79关注 0票数 0

我有一列格式为'2000-01‘的日期,我想相应地将它们转换为'2000q1’。我的问题类似于this post,但我不确定频率函数是如何在那里使用的。我已经写好了这段代码,但它并不健壮,而且效率也很低:

代码语言:javascript
复制
periods = ['2000-01', '2000-02', '2000-03', '2000-04', '2000-05', '2000-06']
lst = []
for quarter in periods:
    year, month = quarter.split('-')[0], quarter.split('-')[1]
    q1, q2, q3, q4 = ['01', '02', '03'], ['04', '05', '06'], ['07', '08', '09'], ['10', '11', '12']
    if month in q1:
        month = 'q1'
    if month in q2:
        month = 'q2'
    if month in q3:
        month = 'q3'
    if month in q4:
        month = 'q4'
    lst.append(year+month)

做这件事最好的方法是什么?干杯:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-04 21:40:01

您可以使用to_periods

代码语言:javascript
复制
periods = ['2000-01', '2000-02', '2000-03', '2000-04', '2000-05', '2000-06']

s = pd.to_datetime(periods, format='%Y-%m').to_period('Q')

输出:

代码语言:javascript
复制
PeriodIndex(['2000Q1', '2000Q1', '2000Q1', '2000Q2', '2000Q2', '2000Q2'], dtype='period[Q-DEC]', freq='Q-DEC')
票数 1
EN

Stack Overflow用户

发布于 2020-05-04 21:41:59

使用PeriodIndex

代码语言:javascript
复制
per = pd.PeriodIndex(periods, freq='Q')
print (per)
PeriodIndex(['2000Q1', '2000Q1', '2000Q1', '2000Q2', '2000Q2', '2000Q2'],
             dtype='period[Q-DEC]', freq='Q-DEC')

如果需要小写q,则添加PeriodIndex.strftime

代码语言:javascript
复制
per = pd.PeriodIndex(periods, freq='Q').strftime('%Yq%q')
print (per)
Index(['2000q1', '2000q1', '2000q1', '2000q2', '2000q2', '2000q2'], dtype='object')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61593594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档