在Pandas列中将日期时间格式化为季度

19

我有一个带有 DateTime 索引中的列的 DataFrame,表示季度,例如:2000-03-31 00:00:00

如何将其转换为 '2000q1'

我已经查看了文档,但它们只提到了DateTimeIndex.quarter

format='%Y%q' 不起作用。选项 on='%Y%q 也不行。


1个回答

34
你可以使用 to_period("Q")
df.index = df.index.to_period("Q")

import pandas as pd
df = pd.DataFrame({"y": [1,2,3]}, 
                  index=pd.to_datetime(["2000-03-31 00:00:00", "2000-05-31 00:00:00", "2000-08-31 00:00:00"]))

df.index = df.index.to_period("Q")
df
#       y
#2000Q1 1
#2000Q2 2
#2000Q3 3

要转换一个普通列col,请使用dt访问系列中的Datetime对象:

df = pd.DataFrame({"y": [1,2,3], 'col': pd.to_datetime(["2000-03-31 00:00:00", "2000-05-31 00:00:00", "2000-08-31 00:00:00"])})


df['col'] = df['col'].dt.to_period("Q")

df
#      col  y
#0  2000Q1  1
#1  2000Q2  2
#2  2000Q3  3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接