Python 以大熊猫为单位将年日期转换为年季度
我有一列格式为“2000-01”的日期,我想将它们相应地转换为“2000q1”。我的问题与类似,但我不确定频率函数在那里是如何使用的。我已经编写了这段代码,它是有效的,但它并不健壮,当然也不高效:Python 以大熊猫为单位将年日期转换为年季度,python,pandas,Python,Pandas,我有一列格式为“2000-01”的日期,我想将它们相应地转换为“2000q1”。我的问题与类似,但我不确定频率函数在那里是如何使用的。我已经编写了这段代码,它是有效的,但它并不健壮,当然也不高效: periods = ['2000-01', '2000-02', '2000-03', '2000-04', '2000-05', '2000-06'] lst = [] for quarter in periods: year, month = quarter.split('-')[0],
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)
最好的方法是什么?干杯:)您可以使用
来
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')
您可以使用设置句点
:
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')
使用:
如果需要小写的q
添加:
使用:
如果需要小写的q
添加:
谢谢,这就是我要找的:)谢谢,这就是我要找的:)