问题描述
我正在寻找一种很好的,可读性和易懂的方式(您下次可以记住的一种方式)将 1996年第三季度转换为熊猫的日期时间,例如本例中的 1996-07-01。
到目前为止,我发现了这个,但是它非常丑陋:
I'm looking for a nice, readable and understandable way (one that you can remember for the next time) to convert 'Q3 1996' to a pandas datetime, for example '1996-07-01' in this case.Until now I found this, but it's mighty ugly:
df = pd.DataFrame({'Quarter':['Q3 1996', 'Q4 1996', 'Q1 1997']})
df['date'] = (
pd.to_datetime(
df['Quarter'].str.split(' ').apply(lambda x: ''.join(x[::-1]))
))
print(df)
Quarter date
0 Q3 1996 1996-07-01
1 Q4 1996 1996-10-01
2 Q1 1997 1997-01-01
我希望以下内容可以工作,因为它可读性强,但不幸的是它没有:
I was hoping the following would work, because it's readable, but unfortunately it doesn't:
df['date'] = pd.to_datetime(df['Quarter'], format='%q %Y')
问题还在于,季度和年份的顺序显然不正确,熊猫无法简单地进行处理。
The problem is also that quarter and year are apparently in the wrong order for pandas to do simple processing.
有人可以帮我找到一种更清洁的方法,将 1996年第三季度转换为大熊猫日期时间吗?
Can anyone help me find a cleaner way of converting 'Q3 1996' to a pandas datetime?
推荐答案
您可以(并且应该)使用 pd.PeriodIndex
作为第一步,然后使用 PeriodIndex.to_timestamp
转换为时间戳:
You can (and should) use pd.PeriodIndex
as a first step, then convert to timestamp using PeriodIndex.to_timestamp
:
qs = df['Quarter'].str.replace(r'(Q\d) (\d+)', r'\2-\1')
qs
0 1996-Q3
1 1996-Q4
2 1997-Q1
Name: Quarter, dtype: object
df['date'] = pd.PeriodIndex(qs, freq='Q').to_timestamp()
df
Quarter date
0 Q3 1996 1996-07-01
1 Q4 1996 1996-10-01
2 Q1 1997 1997-01-01
PeriodIndex
希望您的期间采用%Y-%q
格式。
The initial replace step is necessary as PeriodIndex
expects your periods in the %Y-%q
format.
另一种选择是在执行字符串后使用 pd.to_datetime
更换方法与以前相同。
Another option is to use pd.to_datetime
after performing string replacement in the same way as before.
df['date'] = pd.to_datetime(
df['Quarter'].str.replace(r'(Q\d) (\d+)', r'\2-\1'), errors='coerce')
df
Quarter date
0 Q3 1996 1996-07-01
1 Q4 1996 1996-10-01
2 Q1 1997 1997-01-01
如果性能很重要,您可以拆分并加入,但可以做到干净整洁:
If performance is important, you can split and join, but you can do it cleanly:
df['date'] = pd.to_datetime([
'-'.join(x.split()[::-1]) for x in df['Quarter']])
df
Quarter date
0 Q3 1996 1996-07-01
1 Q4 1996 1996-10-01
2 Q1 1997 1997-01-01
这篇关于一种将 pandas 的季度时间转换为日期时间的干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!