我有一列格式为'2000-01‘的日期,我想相应地将它们转换为'2000q1’。我的问题类似于this post,但我不确定频率函数是如何在那里使用的。我已经写好了这段代码,但它并不健壮,而且效率也很低:
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)做这件事最好的方法是什么?干杯:)
发布于 2020-05-04 21:40:01
您可以使用to_periods
periods = ['2000-01', '2000-02', '2000-03', '2000-04', '2000-05', '2000-06']
s = pd.to_datetime(periods, format='%Y-%m').to_period('Q')输出:
PeriodIndex(['2000Q1', '2000Q1', '2000Q1', '2000Q2', '2000Q2', '2000Q2'], dtype='period[Q-DEC]', freq='Q-DEC')发布于 2020-05-04 21:41:59
使用PeriodIndex
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
per = pd.PeriodIndex(periods, freq='Q').strftime('%Yq%q')
print (per)
Index(['2000q1', '2000q1', '2000q1', '2000q2', '2000q2', '2000q2'], dtype='object')https://stackoverflow.com/questions/61593594
复制相似问题