将 pandas 列中的日期时间格式化为季度
Formatting datetime in pandas columns as Quarters
我有一个 DataFrame
,其中的列在 DateTime
索引中,代表季度,例如:2000-03-31 00:00:00
如何将其转换为 '2000q1'
?
我查看了文档,但他们只提到了 DateTimeIndex.quarter
format='%Y%q'
不起作用。选项 on='%Y%q
也没有
您可以使用 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
我有一个 DataFrame
,其中的列在 DateTime
索引中,代表季度,例如:2000-03-31 00:00:00
如何将其转换为 '2000q1'
?
我查看了文档,但他们只提到了 DateTimeIndex.quarter
format='%Y%q'
不起作用。选项 on='%Y%q
您可以使用 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