gpt4 book ai didi

python - 将字符串转换为日期时间 pandas

转载 作者:行者123 更新时间:2023-11-30 21:53:31 24 4
gpt4 key购买 nike

我正在将数据从 API 提取到 pandas 数据框中,其索引值如下:-

df.index=['Q1-2013',
'Q1-2014',
'Q1-2015',
'Q1-2016',
'Q1-2017',
'Q1-2018',
'Q2-2013',
'Q2-2014',
'Q2-2015',
'Q2-2016',
'Q2-2017',
'Q2-2018',
'Q3-2013',
'Q3-2014',
'Q3-2015',
'Q3-2016',
'Q3-2017',
'Q3-2018',
'Q4-2013',
'Q4-2014',
'Q4-2015',
'Q4-2016',
'Q4-2017',
'Q4-2018']

它是一个字符串值列表。有没有办法将其转换为 pandas 日期时间?我探索了一些问答,它们是关于使用 pd.to_datetime ,它在索引是对象类型时有效。在此示例中,索引值是字符串。预期输出:

new_df=magic_function(df.index)
print(new_df.index[0])
01-2013

想知道如何构建“magic_function”。提前致谢。Q1 是第 1 季度,即 1 月,Q2 是第 2 季度,即 4 月,Q3 是第 3 季度,即 7 月,Q4 是第 4 季度,即 10 月

最佳答案

通过一些操作来使解析工作,您可以使用 pd.PeriodIndex并根据需要设置格式(原因是格式 %Y%q 是预期的):

df.index = [''.join(s.split('-')[::-1]) for s in df.index]
df.index = pd.PeriodIndex(df.index, freq='Q').to_timestamp().strftime('%m-%Y')
print(df.index)

Index(['01-2013', '01-2014', '01-2015', '01-2016', '01-2017', '01-2018',
'04-2013', '04-2014', '04-2015', '04-2016', '04-2017', '04-2018',
'07-2013', '07-2014', '07-2015', '07-2016', '07-2017', '07-2018',
'10-2013', '10-2014', '10-2015', '10-2016', '10-2017', '10-2018'],
dtype='object')
<小时/>

我们还可以使用str.replace获取所需的格式:

df.index = df.index.str.replace(r'(Q\d)-(\d+)', r'\2\1')
df.index = pd.PeriodIndex(df.index, freq='Q').to_timestamp().strftime('%m-%Y')

关于python - 将字符串转换为日期时间 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59644339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com