在大 pandas 列中格式化季度时间 [英] Formatting Quarter time in pandas columns
本文介绍了在大 pandas 列中格式化季度时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 DataFrame
,其中包含 DateTime
索引中的列,表示季度,例如:
I have a DataFrame
with columns in DateTime
index, representing quarters such as:
2000-03-31 00:00:00
如何将其转换为2000q1?
How can I do to transform this into '2000q1'?
我已经查看了文档,但他们只说DateTimeIndex.quarter
这里: http://pandas.pydata。 org / pandas-docs / stable / generated / pandas.DatetimeIndex.quarter.html
I have looked around the docs, but they only say DateTimeIndex.quarter Here: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.quarter.html
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
系列中的对象:
To convert a normal column col
, use dt
to access the Datetime
objects in the series:
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
这篇关于在大 pandas 列中格式化季度时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文